$(document).ready(function () {
    //To check if elements are in the viewport. Used for hiding arrows
    (function ($) { $.belowthefold = function (element, settings) { var fold = $(window).height() + $(window).scrollTop(); return fold <= $(element).offset().top - settings.threshold; }; $.abovethetop = function (element, settings) { var top = $(window).scrollTop(); return top >= $(element).offset().top + $(element).height() - settings.threshold; }; $.rightofscreen = function (element, settings) { var fold = $(window).width() + $(window).scrollLeft(); return fold <= $(element).offset().left + $(element).width() - settings.threshold; }; $.leftofscreen = function (element, settings) { var left = $(window).scrollLeft(); return left >= $(element).offset().left + $(element).width() - settings.threshold; }; $.inviewport = function (element, settings) { return !$.rightofscreen(element, settings) && !$.leftofscreen(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings); }; $.extend($.expr[':'], { "below-the-fold": function (a, i, m) { return $.belowthefold(a, { threshold: 0 }); }, "above-the-top": function (a, i, m) { return $.abovethetop(a, { threshold: 0 }); }, "left-of-screen": function (a, i, m) { return $.leftofscreen(a, { threshold: 0 }); }, "right-of-screen": function (a, i, m) { return $.rightofscreen(a, { threshold: 0 }); }, "in-viewport": function (a, i, m) { return $.inviewport(a, { threshold: 0 }); } }); })(jQuery);

    $('nav#main-menu li').hover(function () {
        var $class = $(this).attr('class');
        if ($class.indexOf(' ') > -1) {
            $class = $class.substr(0, $class.indexOf(' '));
        }
        var $show = $('nav.sub-menu.' + $class);

        if ($show.css('display') === 'none') {
            var $arrow = $('#sub-menu-arrow'),
                $visible = $('nav.sub-menu:visible');

            if ($visible.length) {
                $visible.stop(false, true).slideUp('fast', function () {
                    $arrow.hide();
                    switch ($class) {
                        case 'blue':
                            $arrow.css('left', '280px');
                            break;
                        case 'purple':
                            $arrow.css('left', '465px');
                            break;
                        case 'green':
                            $arrow.css('left', '627px');
                            break;
                    };
                    $arrow.show(0);
                    $show.stop(false, true).slideDown('medium');
                });
            }
            else {
                $arrow.show(0);
                $show.stop(false, true).slideDown('medium');
            }
        }
    });

    var hideMenu;
    $('nav#main-menu li, nav.sub-menu').hover(function () {
        clearTimeout(hideMenu);
    }, function () {
        hideMenu = setTimeout(hideSubMenu, 500);
    });

    function hideSubMenu() {
        $('nav.sub-menu:visible').slideUp('fast', function () {
            $('#sub-menu-arrow').hide();
        });
    }

    //Carousel
    var $scrollBanner = $('#banner-scroll>ul'),
        $scrollBannerVisible = 988,
        $scrollBannerWidth = $scrollBannerVisible / 4 * $('#banner-scroll>ul>li').length,
        $scrollBannerLeft = 0;
    if ($scrollBannerWidth > $scrollBannerVisible) {
        $scrollBanner.width($scrollBannerWidth);

        $('body>aside').click(function (e) {
            var clicked = e.target.id;
            var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();
            if (viewportWidth / 2 > e.pageX) {
                scrollCarousel('left');
            } else {
                scrollCarousel('right');
            }
        });

        function scrollCarousel(moveTo) {
            $scrollBanner.stop(true, true);
            $scrollBannerLeft = parseInt($scrollBanner.css('left').replace('px', ''));
            moveTo = moveTo ? moveTo : 'right';

            if (moveTo === 'left') {
                if ($scrollBannerLeft) {
                    $scrollBanner.animate({
                        left: '+=' + $scrollBannerVisible
                    }, 500);
                } else {
                    var $swapSidePos = ($scrollBannerWidth - $scrollBannerVisible);
                    if ($swapSidePos == $scrollBannerVisible) {
                        $swapSidePos = 0;
                    }
                    $swapSidePos += $scrollBannerVisible - ($swapSidePos % $scrollBannerVisible);
                    $scrollBanner.animate({
                        left: '-' + ($swapSidePos) + 'px'
                    }, 500);
                }
            } else if (moveTo === 'right') {
                if ($scrollBannerLeft > ($scrollBannerWidth - $scrollBannerVisible) / -1) {
                    $scrollBanner.animate({
                        left: '+=-' + $scrollBannerVisible
                    }, 500);
                } else {
                    $scrollBanner.animate({
                        left: '0px'
                    }, 500);
                }
            }
        }

        $(window).bind('scroll', function (event) {
            $("#banner-arrow-right:in-viewport").show();
            $("#banner-arrow-right:right-of-screen").hide();
        });
        $(window).bind('resize', function (event) {
            $("#banner-arrow-right:in-viewport").show();
            $("#banner-arrow-right:right-of-screen").hide();
        });
        $(window).load(function (event) {
            $("#banner-arrow-right:in-viewport").show();
            $("#banner-arrow-right:right-of-screen").hide();
        });
    } else {
        $('#banner-content>img').hide();
    }

    //Homepage
    if ($('#home-content').length) {
        var moveBanner,
            $scroll = $('#home-scroll>ul'),
            $scrollWidth = 950 * $('#home-scroll>ul>li').length,
            timeout = 6000;

        if ($scrollWidth > 950) {
            $scroll.width($scrollWidth);

            $('#main').click(function (e) {
                var clicked = e.target.id;
                if (clicked === 'main' || clicked === 'home-arrow-right' || clicked === 'home-arrow-left') {
                    var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();
                    if (viewportWidth / 2 > e.pageX) {
                        scrollBanner('left');
                    } else {
                        scrollBanner('right');
                    }
                }
            });

            function scrollBanner(moveTo) {
                clearTimeout(moveBanner);
                $scroll.stop(true, true);

                moveTo = moveTo ? moveTo : 'right';

                if (moveTo === 'left') {
                    if ($scroll.css('left') != '0px') {
                        $scroll.animate({
                            left: '+=950'
                        }, 500, function () {
                            moveBanner = setTimeout(scrollBanner, timeout);
                        });
                    }
                    else {
                        $scroll.animate({
                            left: '-' + ($scrollWidth - 950) + 'px'
                        }, 500, function () {
                            moveBanner = setTimeout(scrollBanner, timeout);
                        });
                    }
                }
                else if (moveTo === 'right') {
                    if ($scroll.css('left') != '-' + ($scrollWidth - 950) + 'px') {
                        $scroll.animate({
                            left: '+=-950'
                        }, 500, function () {
                            moveBanner = setTimeout(scrollBanner, timeout);
                        });
                    }
                    else {
                        $scroll.animate({
                            left: '0px'
                        }, 500, function () {
                            moveBanner = setTimeout(scrollBanner, timeout);
                        });
                    }
                }
            }

            moveBanner = setTimeout(scrollBanner, timeout);

            $(window).bind('scroll', function (event) {
                $("#home-arrow-right:in-viewport").show();
                $("#home-arrow-right:right-of-screen").hide();
            });
            $(window).bind('resize', function (event) {
                $("#home-arrow-right:in-viewport").show();
                $("#home-arrow-right:right-of-screen").hide();
            });
            $(window).load(function (event) {
                $("#home-arrow-right:in-viewport").show();
                $("#home-arrow-right:right-of-screen").hide();
            });

            $('div.inner-circle').hover(function () {
                clearTimeout(moveBanner);
            }, function () {
                moveBanner = setTimeout(scrollBanner, timeout);
            });
        } else {
            $('#home-content>img').hide();
        }
    }

    //Overview
    if ($('#detail-left ul.level-2').length) {
        var $detailContent = $('.detail-content');
        var $activeLevel2 = $('#detail-left ul.level-2.active');
        $detailContent.height($activeLevel2.height());
        var $currentElement;
        var $level2;
        var $target;
        $('#detail-left ul.level-1>li').has('ul.level-2').attr('onclick', '').each(function () {
            $(this).click(function (e) {
                e.preventDefault();
                $currentElement = $(this);
                $level2 = $currentElement.children('ul:first');
                if ($level2.is(':hidden') || $level2.css('width') == '0px') {
                    $('#detail-left ul.level-1>li.active').removeClass('active');
                    
                    $currentElement.addClass('active');
                    $('#detail-left section.level-3:visible').each(function () {
                        if (!$(this).parent().parent().hasClass ('single')) {
                            $(this).hide('fast').removeClass('active').parent().removeClass('active');
                        }
                    });
                    $('#detail-left ul.level-2:visible').each(function () {
                        if ($(this) != $level2) {
                            $(this).removeClass('active');
                        }
                    });
                    $level2.addClass('active');
                    //$detailContent.animate({
                    //    height: ($('#detail-left ul.level-2.active>li').length * 45) + 'px'
                    //});
                    /*if (typeof (window.history.pushState) == 'function') {
                        history.pushState({ level: '1' }, '', $currentElement.children('a:first').attr('href'));
                    }*/
                } else {
                    if (!$(e.target).parents('#detail-left ul.level-2:visible').length) {
                       // $('#detail-left section.level-3:visible').hide('fast').removeClass('active').parent().removeClass('active');
                        $('#detail-left ul.level-2:visible').removeClass('active');
                        $detailContent.animate({
                            //height: '0px'
                        });
                    }
                }
            });
        });
        if ($('#detail-left section.level-3').length) {
            var $level3;
            $('#detail-left ul.level-2>li').has('section.level-3').attr('onclick', '').each(function () {
                $(this).click(function (e) {
                    e.preventDefault();
                    if (e.target.tagName.toLowerCase() != 'section' && $(e.target).parent().has('section').length) {
                        $currentElement = $(this);
                        $level3 = $currentElement.children('section:first');
                        if ($level3.is(':hidden')) {
                            $('#detail-left ul.level-2>li.active').removeClass('active');
                            $currentElement.addClass('active');
                            $(this).parent ().find ('section.level-3:visible').hide('fast').removeClass('active');
                            if ($detailContent.height() < $('#detail-left ul.level-2.active>li').length * 45) {
                                $detailContent.animate({
                                    height: (($('#detail-left ul.level-2.active>li').length * 45) + $level3.height()) + 'px'
                                });
                            }
                            $level3.show('fast');
                            $(this).addClass('active');
                            /*if (typeof (window.history.pushState) == 'function') {
                                history.pushState({ level: '2' }, '', $currentElement.children('a:first').attr('href'));
                            }*/
                        } else {
                            $('#detail-left ul.level-2>li.active').removeClass('active');
                            $('#detail-left section.level-3:visible').hide('fast').removeClass('active');
                            if ($detailContent.height() < $('#detail-left ul.level-2.active>li').length * 45) {
                                $detailContent.animate({
                                    height: ($('#detail-left ul.level-2.active>li').length * 45) + 'px'
                                });
                            }
                        }
                    }
                });
            });
        }
        /*window.onpopstate = function (event) {
            $('#detail-left ul .active').removeClass('active');
            if (event.state) {
                var path = document.location.toString();
                path = path.replace('http://', '').replace('https://', '');
                path = path.replace(path.split('/')[0], '');
                $('#detail-left .level-' + event.state.level + ' a').each(function () {
                    $currentElement = $(this);
                    if ($currentElement.attr('href') == path) {
                        $currentElement.siblings().addClass('active').show();
                        $currentElement.parentsUntil('.level-1').addClass('active');
                        return false;
                    }
                });
            }
            $detailContent.animate({
                height: (($('#detail-left ul.level-2.active>li').length * 45) + $level3.height()) + 'px'
            });
        }*/
    }
    var $submitButtons = $('form .w3s_Row input[type="submit"]');
    if ($submitButtons.length && $submitButtons.parent().siblings().length == 1) {
        $submitButtons.parent().css('float', 'right').parent().css('float', 'right').parent().addClass('clearfix');
    }

    if ($('#map_canvas').length) {
        var geocoder = new google.maps.Geocoder(),
                options,
                map,
                marker;

        geocoder.geocode({ 'address': $('#contact-address').html() + ', ' + $('#contact-zipcode').html() + ' ' + $('#contact-city').html() }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                options = {
                    zoom: 14,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    disableDefaultUI: true
                };
                map = new google.maps.Map(document.getElementById("map_canvas"), options);
                marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    title: "ROC Rivor",
                    animation: google.maps.Animation.DROP
                });
                google.maps.event.addListener(marker, 'click', function () {
                    if (marker.getAnimation() != null) {
                        marker.setAnimation(null);
                    } else {
                        marker.setAnimation(google.maps.Animation.BOUNCE);
                    }
                });
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }

    if ($('.faq').length) {
        var $currentArticle,
                $show;
        $('.faq article header').click(function () {
            $currentArticle = $(this).parent();
            $show = !($currentArticle.hasClass('active'));
            $('.faq article.active').each(function () {
                $(this).children('p').hide('fast', function () {
                    $('.faq article').removeClass('active');
                });
            });

            if ($show) {
                $currentArticle.children('p').show('medium', function () {
                    $currentArticle.addClass('active');
                });
            }
        });
    }

    $('#loginlink').click(function() {
        if($('#login_arrow').is(':visible')) {
            $('#login').slideUp(100, function() {
                $('#login_arrow').slideUp(100);
            });
        } else {
            $('#login_arrow').slideDown(100, function() {
                $('#login').slideDown(100);
            });
        }
    });
    
    !$('.content.text p').length || $('ul.level-1 li.active.current ul').removeClass('active');
});
function openRoute() {
    var l_strUrl = 'http://maps.google.nl/maps?f=d&source=s_d&&daddr=' +
        $('#contact-address').html() + ', ' + $('#contact-zipcode').html() + ' ' + $('#contact-city').html();
    window.open(l_strUrl);
}

function checkForm(p_strFormId) {
    $('#Verstuur').hide();
    $('#Loading').show();
    var l_blnIsValid = true;
    $('#' + p_strFormId + ' :input').each(function (i) {
        if ((this.name.substring(0, 1) == 1 || this.value.length > 0) && this.type != 'select-one' && this.type != 'submit' && this.id.length > 0 && !isValidInput(this.value, this.name.substring(1, 4))) {
            alert(this.id + ' is niet valide');
            this.focus();
            l_blnIsValid = false;
            $('#Verstuur').show();
            $('#Loading').hide();
            return false;
        }
    });
    return l_blnIsValid;
}

function isValidInput(p_strValue, p_strType) {
    var isValid = false;
    switch (p_strType) {
        case 'tx2':
            isValid = true;
            break;
        case 'txt':
            isValid = new RegExp(/^[a-z|\s]+$/gi).test(p_strValue);
            break;
        case 'var':
            isValid = new RegExp(/^[\w|\s|,|\.|\?|!|\=|\+|\-|%]+$/gi).test(p_strValue);
            break;
        case 'zip':
            isValid = new RegExp(/^\d{4}\s?[a-z]{2}$/gi).test(p_strValue);
            break;
        case 'hnr':
            isValid = new RegExp(/^\d{1,4}[a-z]?$/gi).test(p_strValue);
            break;
        case 'tel':
            isValid = new RegExp(/^0\d{9}$/gi).test(p_strValue);
            break;
        case 'int':
            isValid = new RegExp(/^\d+$/gi).test(p_strValue);
            break;
        case 'dtm':
            if (p_strValue != 'dd-mm-jjjj') {
                isValid = new RegExp(/^\d{2}-\d{2}-\d{4}$/gi).test(p_strValue);
            }
            break;
        case 'dbl':
            isValid = new RegExp(/^\d+?(,+\d{2})?$/g).test(p_strValue);
            break;
        case 'eml':
            isValid = new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/gi).test(p_strValue);
            break;
    }
    return isValid;
}
function CheckNewsletterForm () {
    var input = $ ('#Email');
    var isValid = new RegExp (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/gi).test (input.val ());
    if (!isValid) {
        alert ('Het ingevoerde emailadres is niet geldig.');
        input.focus ()
    }
    return isValid;
}
function OpenVideo(p_strYoutubeId, p_strTitle) {
    $('#VideoBox .OverlayCenterBox').html (
        '<object width="600" height="485">' +
        '<param name="movie" value="http://www.youtube.com/v/' + p_strYoutubeId +'?fs=0" />' +
        '<param name="allowFullScreen" value="true"></param>' +
        '<param name="allowScriptAccess" value="always"></param>' +
        '<embed src="http://www.youtube.com/v/' + p_strYoutubeId + '?fs=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="600" height="485"></embed>' +
        '</object>');
    $('#VideoBox').show('fast');
}
function CloseVideo() {
    $('#VideoBox').hide('fast');
    $('#VideoBox .OverlayCenterBox').empty();
}
