app_layout = {
    loader: (function () {
        return {
            show: function () {
                $('#app_loader_wrapper').slideDown();
            },
            hide: function (callback) {
                var func_callback = callback ||
                function () {};
                $('#app_loader_wrapper').delay(100).slideUp(function () {
                    func_callback();
                });
            },
            create: function () {
                $('body').append('<div id="app_loader_wrapper"><div class="center"><img src="/images/ajax-loader.gif" /></div></div>');
                $('#app_loader_wrapper').hide();
            }
        }
    }()),
    emaillink: function () {
        $('a').each(function () {
            if ($(this).text().indexOf('info@studeur.nl') > -1) {
                $(this).attr('href', 'mailto:info@studeur.nl');
            }
        });
    },
    faq: function () {
        var curIndex = app_utils.cookieExist('selectedForm') ? app_utils.getCookie('selectedForm') : 0;
        
        $('.faq dt').live('click', function () {
            if ($(this).next().is(':hidden')) {
                $('.faq dd').stop().hide();
                $(this).next().stop().show();
                $('html, body').scrollTop($(this).offset().top - 150);
                app_utils.setCookie('selectedForm', $('.faq dt').index(this));
            } else {
                $(this).next().stop().hide();
            }
        });

        if ($('.faq form input.error').length > 0) {
            $('.faq dd').stop().hide();
            $('.faq dt').eq(curIndex).next().show();
            $('html, body').animate({scrollTop : $('.faq dt').eq(curIndex).next().find('form').offset().top - 150}, 500);
        }
    },
    showFormErrors: function (form) {
        if (form.length > 0) {
            form.prepend('<div class="messages error"><ul class="errors"></ul></div>').find('.messages').hide();
        }
        return {
            show: function (errors) {
                var errorsRows = [];
                $.each(errors, function (key, value) {
                    errorsRows.push('<li id="' + key + '"><strong>' + key + ':</strong>' + value.isEmpty + '</li>');
                });
                form.find('.messages').hide().find('ul.errors').html(errorsRows.join("\n")).closest('.messages').slideDown('slow', function () {
                    $('body, html').scrollTop(form.position().top - 150);
                });
            }
        }
    },
    largeTip: (function () {
        return {
            close: function () {
                $('.app_largeTipWrapper').fadeOut('fast', function () {
                    $(this).remove()
                });
            },
            container: function () {
                return $('.app_largeTipWrapper');
            },
            open: function (content, append) {
                var appendHtml = append || '',
                    largeWrapper = $('<div/>', {
                        'class': 'app_largeTipWrapper',
                        html: '<div class="blokker"></div><div class="content"><div class="contHolder">' + content + '</div>' + appendHtml + '<div class="tip"></div><a class="sluiten" href="#">sluiten</a></div>'
                    }).hide().appendTo('body').fadeIn(),
                    marginTop;
                marginTop = function () {
                    return $(window).scrollTop() + (($(window).height()) / 2);
                };
                $(window).scroll(function () {
                    largeWrapper.find('.content').css({
                        top: marginTop()
                    });
                });
                largeWrapper.find('.content').css({
                    top: marginTop()
                });
                largeWrapper.find('.sluiten, .blokker').click(function () {
                    app_layout.largeTip.close();
                });
            }
        }
    }()),
    products: function () {
        app_utils.trimText($('form.cursusGroepen label span, .groepOverview h5'), 10);
        app_interactive.tooltips();
    },
    showMiniMessage: (function () {
        return {
            show: function (dom, message) {
                if (dom.length > 0) {
                    if ($('#app_miniMessage').length > 0) {
                        $('#app_miniMessage').remove();
                    }
                    $('body').append('<div id="app_miniMessage"><div class="content">' + message + '</div><div class="tip"></div></div>');
                    $('#app_miniMessage').css({
                        left: dom.offset().left - ($('#app_miniMessage').width() / 2) + 20,
                        top: dom.offset().top - ($('#app_miniMessage').height() + 30)
                    });
                    $(window).scroll(function () {
                        $('#app_miniMessage').fadeOut('slow', function () {
                            $('#app_miniMessage').remove();
                        });
                    });
                    setTimeout(function () {
                        $('#app_miniMessage').fadeOut('slow', function () {
                            $('#app_miniMessage').remove();
                        });
                    }, 2000);
                }
            },
            remove: function () {
                if ($('#app_miniMessage').length > 0) {
                    $('#app_miniMessage').remove();
                }
            }
        }
    }())
};
app_interactive = {
    tabbedForm: function (formParent, type) {
        var typeElem = type || 'div',
            ulNav, errorIndex = 0;
        ulNav = $('<ul/>', {
            'class': 'app_tabbed_nav',
            html: ''
        });
        if (formParent.find(typeElem).length > 0) {
            formParent.find(typeElem).each(function () {
                if (typeElem === 'form') {
                    if ($(this).find('legend').length > 0) {
                        if($(this).hasClass('current')) {
                            ulNav.append('<li class="current">' + $(this).find('legend').html() + '</li>');
                        } else {
                            ulNav.append('<li>' + $(this).find('legend').html() + '</li>');
                        }
                    }
                }
            });
            if (formParent.find(typeElem + ' input.error').length > 0) {
                errorIndex = formParent.find(typeElem + ' input.error').closest(typeElem).index();
                formParent.find(typeElem).eq(errorIndex).addClass('current');
                ulNav.find('li').eq(errorIndex).addClass('current');
            } 
            ulNav.find('li').click(function () {
                var index = $(this).index();
                ulNav.find('li').removeClass('current');
                formParent.find(typeElem).removeClass('current');
                $(this).addClass('current');
                formParent.find(typeElem).eq(index).addClass('current');
            });
            formParent.prepend(ulNav);
        }
    },
    filterTool: function () {
        var collapsedTool = {
            collapsed: true
        },
            collapseFilter, setCollProducts, collapsedProducts = {
                collapsed: false
            };
        collapseFilter = function () {
            if (collapsedTool.collapsed) {
                collapsedTool.collapsed = false;
                $('.filter .toolCollapse').removeClass('collapsed');
                $('.filter .toolCollapse').closest('.filter').find('ul.ul_form, ul.tools, div.label_tabs').slideDown();
            } else {
                collapsedTool.collapsed = true;
                $('.filter .toolCollapse').closest('.filter').find('ul.ul_form, ul.tools, div.label_tabs').slideUp();
                $('.filter .toolCollapse').addClass('collapsed');
            }
        }
        setCollProducts = function () {
            if (collapsedProducts.collapsed) {
                $('#overz_rows').addClass('selected');
                $('#disc_rows').removeClass('selected');
                $('.trimmester dt h3').addClass('collapsed');
                $('.trimmester dd').hide();
            } else {
                $('#disc_rows').addClass('selected');
                $('#overz_rows').removeClass('selected');
                $('.trimmester dd').show();
            }
        };
        $('.filter .toolCollapse').live('click', function () {
            app_utils.setCookie('collapsedtool', app_utils.stringify(collapsedTool));
            collapseFilter();
            return false;
        });
        $('#overz_rows').live('click', function () {
            $(this).addClass('selected');
            $('#disc_rows').removeClass('selected');
            collapsedProducts.collapsed = true;
            $('.trimmester dt h3').addClass('collapsed');
            app_utils.setCookie('collapsedProducts', app_utils.stringify(collapsedProducts));
            $('.trimmester dd').hide();
            return false;
        });
        $('#disc_rows').live('click', function () {
            $(this).addClass('selected');
            $('#overz_rows').removeClass('selected');
            collapsedProducts.collapsed = false;
            $('.trimmester dt h3').removeClass('collapsed');
            app_utils.setCookie('collapsedProducts', app_utils.stringify(collapsedProducts));
            $('.trimmester dd').show();
            return false;
        });

        $('.trimmester dt a, .trimmester dt').click(function () {
            if ($(this).closest('dl').find('dd').is(':hidden')) {
                $(this).closest('dl').find('h3').removeClass('collapsed');
                $(this).closest('dl').find('dd').show();
            } else {
                $(this).closest('dl').find('h3').addClass('collapsed');
                $(this).closest('dl').find('dd').hide();
            }
            return false;
        });
        if (app_utils.cookieExist('collapsedtool')) {
            collapsedTool = app_utils.toObject(app_utils.getCookie('collapsedtool'));
            collapseFilter();
        }
        if (app_utils.cookieExist('collapsedProducts')) {
            collapsedProducts = app_utils.toObject(app_utils.getCookie('collapsedProducts'));
            setCollProducts();
        }
    },
    assets: function () {
        $('div#quote a').click(function () {
            if ($('#etalage').length) {
                $('html, body').animate({
                    scrollTop: 0
                }, 500);
                return false;
            }
        });
    },
    fixedTools: function () {
        var topOffset, topCart;
        if ($('.header_products .filter').length > 0) {
            topOffset = $('.header_products .filter').length > 0 ? $('.header_products .filter').offset().top - 20 : 0, topCart = $('.stipedBoxes.winkel').length > 0 ? $('.stipedBoxes.winkel').offset().top - 25 : 0;
            $(window).scroll(function () {
                if ($(document).scrollTop() >= topOffset && $(document).scrollTop() <= $('#shopContent').offset().top + $('#shopContent').height() - 120) {
                    $('.header_products .filter').closest('#shopContent').addClass('fixed');
                } else {
                    $('.header_products .filter').closest('#shopContent').removeClass('fixed');
                }
                if ($(document).scrollTop() >= topCart && $(document).scrollTop() <= $('#shopContent').offset().top + $('#shopContent').height() - 230) {
                    $('.stipedBoxes.winkel').addClass('fixed');
                    $('.stipedBoxes').hide();
                    $('.stipedBoxes.winkel').show();
                } else {
                    $('.stipedBoxes.winkel').removeClass('fixed');
                    $('.stipedBoxes').show();
                }
            });
        }
    },
    shop: function () {
        var addProd = '/format/json',
            populateTable, trimRowText, fixFloats;
        fixFloats = function (floatInt) {
            return floatInt.toString().split('.')[1].length === 1 ? floatInt.toString() + '0' : floatInt.toString();
        }
        trimRowText = function () {
            app_utils.trimText($('div.winkel span.label em'), 20);
            app_utils.trimText($('div.downloadRows h3'), 55);
        };
        /*$('#register_step1').submit(function () {
            // if ($('#register_step1-voorwaarde:checked').length > 0) {
                // return true;
            // } else {
                // $('#register_step1-voorwaarde').next().addClass('errorLabel');
                // return false;
            // }
        });*/
        $('#automatischeIncasso input').attr('checked', 'checked');
        $('div.selectPayment label').click(function () {
            $('div.selectPayment').removeClass('opend');
            $('#betaalMethodes form').hide()
            $(this).closest('div.selectPayment').addClass('opend').next().show();
        });
        $('.opend').each(function () {
            $(this).next().show();
        });
        populateCartTable = function (data) {
            var html = '',
                formatTotalPrice
                total = 0,
                totalItems = 0;
            formatTotalPrice = function (total) {
                return total.toString().substring(1, total.toString().length);
            };
            if (data.order !== undefined) {
                if ($('.stipedBoxes.winkel div.content_cart').length < 1) {
                    $('.stipedBoxes.winkel h4').after('<div class="content_cart"></div>');
                }
                app_utils.objectMap(data.order.orderLines, function (key, value) {
                    var zebra = app_utils.toggleB.toggle() ? 'even' : 'oneven';
                    html += '<div class="row ' + zebra + '">';
                    html += '   <span class="label">';
                    html += '       <span>' + value.qty + 'x</span>';
                    html += '       <em title="">' + value.name + '</em>';
                    html += '   </span>';
                    html += '   <em>&euro; ' + value.lineTotal + '</em>';
                    html += '</div>';
                    totalItems += value.qty;
                });
                total += data.order.total;
            }
            $('#tools span.cartItems').html(totalItems);
            $('.stipedBoxes.winkel div.total em').html('&euro; ' + formatTotalPrice(total));
            $('.stipedBoxes.winkel div.content_cart').html(html);
            trimRowText();
        };
        $('#shop_cart dd a').click(function () {
            if (!$(this).hasClass('infoTitle')) {
                app_layout.loader.show();
                $('#shop_cartHolder').load($(this).attr('href'), function () {
                    app_layout.loader.hide();
                });
            }
            return false;
        });
        
        if ($('form.cursusGroepen input[type="radio"]').length > 0 ) {
           $('form.cursusGroepen input[type="radio"]').click(function () {
                var top = $.browser.msie ? $.browser.version < 9 ? 30 : 50 : 50;
                $(this).closest('form').find('.btnWrapper').addClass('green').css({
                    top: $(this).parent().position().top - top
                });
            }); 
        }
       
       $('form.cursusGroepen .btnWrapper, li .btnWrapper.shop ').click(function () {
            var _this = $(this),
                addToCart;
            app_layout.loader.show();
            addToCart = function () {
                var prodId = _this.closest('dl').find('dt').length > 0  ?  _this.closest('dl').find('dt').attr('rel') : _this.closest('li').attr('rel');
                    addToCartHref = '/shop/order/add/product/' + prodId,
                    radioExists = _this.closest('form').find('input[type="radio"]').length > 0,
                    groepen = radioExists ? '/groep/' : '',
                    groepId = radioExists ? _this.closest('form').find('input:checked').val() : '',
                    periodeId = radioExists ? '/periode/' + _this.closest('form').find('input:checked').attr('class').replace('periode_', '') : '';
                
                qty = '/qty/1';
                app_layout.loader.show();
                console.log(_this.closest('dl').find('dt').length);
                $.get(addToCartHref + groepen + groepId + periodeId + addProd, function (data) {
                    if (data.error !== undefined) {
                        app_utils.disabled(_this);
                        app_layout.showMiniMessage.show(_this, data.error);
                    } else {
                        _this.closest('.btnWrapper').removeClass('green');
                        app_utils.highlight($('.stipedBoxes.winkel'), '#4C93C3', '#FFFFFF');
                        populateCartTable(data);
                    }
                    app_layout.largeTip.close();
                    app_layout.loader.hide();
                });
                return false;
            };
            if ($(this).closest('form').find('input[type="radio"]').length > 0) {
                if (!$(this).closest('form').find('input:checked').length) {
                    app_layout.showMiniMessage.show($(this), 'Kies eerst een groep');
                    app_layout.loader.hide();
                    return false;
                }
            }
            addToCart();
            return false;
        });
        
        $('#betaalMethodes input[type="radio"]').change(function () {
            $(this).closest('form').attr('action', '/' + $(this).val());
        });
        trimRowText();
    },
    filterBox: function () {
        var htmlTemplate = $('#shopContent div.trimmester dt').eq(0).html(),
            urls = ['cursus/', 'samenvattingen/', 'tentamen/'],
            handleRequest, miniFilterPeriodeSelect = $('.header_products .ul_form li').eq(2),
            miniFilterJaarSelect = $('.header_products .ul_form li').eq(1),
            postAfter, filterPeriodeSelect = $('#tools form dd').eq(3),
            filterJaarSelect = $('#tools form dd').eq(2),
            disableSelectBoxes;
        disableSelectBoxes = function (type) {
            if (type === 'mini') {
                miniFilterPeriodeSelect.find('select').attr('disabled', 'disabled');
                miniFilterJaarSelect.find('select').attr('disabled', 'disabled');
            } else {
                filterPeriodeSelect.find('select').attr('disabled', 'disabled');
                filterJaarSelect.find('select').attr('disabled', 'disabled');
            }
        };
        handleRequest = function () {
            setTimeout(function () {
                app_layout.loader.hide();
            }, 1000);
        };
        $('#tools .cart span').click(function () {
            window.location.href = $(this).find('a').attr('href');
        });
        $('#tools form select').change(function () {
            var url = '/' + $('#tools form dd').eq(1).find('option:selected').attr('label').toString().toLowerCase() + '/';
            $(this).closest('form').attr('action', url);
            if ($(this).closest('dd').eq(0).find('option:first-child').attr('selected') === 'selected') {
                disableSelectBoxes();
            } else {
                if ($(this).closest('dd').index() < 4) {
                    app_layout.loader.show();
                    $('#tools form dd').eq(5).find('select option:first-child').attr('selected', 'selected');
                    $.post(url + 'format/json/', app_utils.getFormValues($(this).closest('form')), function (data) {
                        var options = '<option value="0" label="maak een keuze">maak een keuze</option>';
                        app_layout.loader.hide();
                        if (!app_utils.objectEmpty(data.products) && typeof (data.products) === 'object') {
                            app_utils.objectMap(data.products, function (key, data) {
                                options += '<option value="' + data[0].period_id + '" label="' + key + '">' + key + '</option>'
                                filterPeriodeSelect.find('select').html(options);
                            });
                            filterPeriodeSelect.find('select').removeAttr('disabled');
                            filterJaarSelect.find('select').removeAttr('disabled');
                            app_utils.highlight(filterPeriodeSelect.find('select').closest('dd'), '#669A01', '#FFF', 2);
                            app_utils.highlight(filterJaarSelect.find('select').closest('dd'), '#669A01', '#FFF', 2);
                            
                        } else {
                            filterPeriodeSelect.find('select').html(options);
                            disableSelectBoxes();
                        }
                    });
                }
            }
        });
        $('.header_products .filter select').change(function () {
            var url = $(this).closest('form').attr('action'),
                thisSelect = $(this);
            if ($(this).parent().eq(0).find('option:first-child').attr('selected') === 'selected') {
                disableSelectBoxes('mini');
            } else {
                if ($(this).parent().index() < 2) {
                    var options = '<option value="0" label="maak een keuze">maak een keuze</option>';
                    app_layout.loader.show()
                    $('#shopHolderLeft .ul_form li:last-child select option:first-child').attr('selected', 'selected');
                    $.post(url + 'format/json/', app_utils.getFormValues($(this).closest('form')), function (data) {
                        app_layout.loader.hide();
                        
                        postAfter(url, thisSelect);
                        if (!app_utils.objectEmpty(data.products) && typeof (data.products) === 'object') {
                            app_utils.objectMap(data.products, function (key, data) {
                                options += '<option value="' + data[0].period_id + '" label="' + key + '">' + key + '</option>'
                                miniFilterPeriodeSelect.find('select').html(options);
                            });
                            miniFilterPeriodeSelect.find('select').removeAttr('disabled');
                            miniFilterJaarSelect.find('select').removeAttr('disabled');
                            app_utils.highlight(miniFilterPeriodeSelect.find('select').closest('li'), '#669A01', '#FFF', 2);
                            app_utils.highlight(miniFilterJaarSelect.find('select').closest('li'), '#669A01', '#FFF', 2);
                        } else {
                            filterPeriodeSelect.find('select').html(options);
                            disableSelectBoxes();
                        }
                        
                    });
                } else {
                    app_layout.loader.show()
                    postAfter(url, thisSelect);
                }
            }
            $(document).scrollTop(0);
            $(this).closest('form').submit(function () {
                return false;
            });
        });
        $('#tools form').submit(function () {
            $(this).closest('form').attr('action', '/' + $('#tools form #soort option:selected').html().toLowerCase() + '/');
        });
        $('#tools form #soort').change(function () {
            $(this).closest('form').attr('action', '/' + urls[$(this).val()]);
        });
        postAfter = function (url, thisSelect) {
            $.ajax({
                url: url,
                success: function (data) {
                    app_layout.loader.hide();
                    $('#shopContent .trimmester').html($(data).find('.trimmester').html());
                    app_layout.products();
                    app_interactive.filterTool();
                    app_interactive.shop();
                },
                data: app_utils.getFormValues($(thisSelect).closest('form'))
            })
        };
        disableSelectBoxes('mini');
        disableSelectBoxes();
    },
    form: function () {
        if ($(".calendar input").length > 0) {
            $(".calendar input").datepicker({
                yearRange: '1950:+1m +1w',
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true
            });
        }
        $('div.incasso a.btn, div.ideal a.btn').click(function () {
            if ($(this).closest('.coll').hasClass('incasso')) {
                $(this).closest('.coll').find('form').show();
                $(this).hide();
            } else {
                $('.idealForm input[type="submit"]').trigger('click');
            }
            return false;
        });
    },
    loginBox: (function () {
        return {
            show: function () {
                if ($('#app_fancy_login form').length === 0) {
                    app_layout.loader.show();
                    $('#app_fancy_login .content').load('/login/ #logginForm', function () {
                        app_layout.loader.hide(function () {
                            $('#app_fancy_login').show();
                        });
                    });
                } else {
                    $('#app_fancy_login').show();
                }
            },
            hide: function () {
                $('#app_fancy_login').hide();
            },
            create: function () {
                if ($('#app_fancy_login').length > 0) {
                    $('body').remove('#app_fancy_login');
                }
                $('body').append('<div id="app_fancy_login"><a href="#" class="app_tab_blocker">sluiten</a><div class="content"></div></div>');
                $('#app_fancy_login').hide();
                if ($('.nav .inloggen').length > 0) {
                    $('#app_fancy_login').css({
                        left: $('.nav .inloggen').offset().left - 20
                    });
                }
                $('#app_fancy_login .app_tab_blocker').width($('.nav .inloggen').width());
                $('#app_fancy_login .app_tab_blocker').click(function () {
                    app_interactive.loginBox.hide();
                });
                $('.nav .inloggen').click(function () {
                    if ($(this).parent().find('ul').length === 0) {
                        app_interactive.loginBox.show();
                        return false;
                    }
                });
                $('#bun').click(function () {
                    app_interactive.loginBox.hide();
                });
            }
        }
    }()),
    tooltips: function () {
        $('.info, .cursus, .tools li a').each(function () {
            $(this).easyTooltip({
                xOffset: -60,
                yOffset: -20,
                content: $(this).text(),
                width: 150
            });
        });
        $('.addBtn, .infoTitle').easyTooltip({
            xOffset: -60,
            yOffset: -20,
            width: 150
        });
    },
    handleFormSubmit: function () {
        if ($('form').length > 0) {
            $('form').each(function () {
                var curForm = $(this),
                    formErrors = app_layout.showFormErrors(curForm);
                if (!$(this).hasClass('standart')) {
                    $(this).submit(function () {
                        app_layout.loader.show();
                        $.post($(this).attr('action') + $(this).handleSubmit.getRequestType(), app_utils.getFormValues($(this)), function (data) {
                            app_layout.loader.hide();
                            if (data.formError !== undefined) {
                                $.each(data.formError, function (key, value) {
                                    $('input[name="' + key + '"], select[name="' + key + '"], textarea[name="' + key + '"]').addClass('error').parent().addClass('pError');
                                });
                                formErrors.show(data.formError);
                            } else {
                                if (curForm.handleSubmit !== undefined) {
                                    curForm.handleSubmit.onsubmit(data);
                                }
                                curForm.success = true;
                            }
                        });
                        return false;
                    });
                }
            });
        }
    }
};
app_scrollBar = {
    start: function (o) {
        var scrollPane, scrollContent, $ = jQuery,
            padding = o.padding || 25,
            counter = 0,
            scrollThePanel;
        if (o.scrollPane !== undefined) {
            scrollPane = o.scrollPane;
        } else {
            throw "ScrollBar obj not found: scrollPane";
        }
        if (o.scrollContent !== undefined) {
            scrollContent = o.scrollContent;
            scrollContent.width(scrollContent.find('li').length * (scrollContent.find('li').eq(0).width() + padding));
        } else {
            throw "ScrollBar obj not found: scrollContent";
        }
        scrollPane.parent().append('<div class="toolbarScrolling"><a href="#" class="rightArrow">&raquo;</a><a href="#" class="leftArrow">&laquo;</a><div class="scroll-bar-wrap ui-widget-content ui-corner-bottom"><div class="scroll-bar"></div></div></div>');
        scrollThePanel = function (val) {
            var handleScroll = Math.round(
            val / 100 * (scrollPane.width() - scrollContent.width())) * -1;
            scrollPane.stop().animate({
                scrollLeft: handleScroll
            }, 250);
        };
        $('.toolbarScrolling .rightArrow').click(function () {
            counter = counter > 4 ? 5 : counter + 1;
            var partMover = counter * 20;
            scrollThePanel(partMover);
            $('.ui-slider-handle').animate({
                left: partMover + '%'
            }, 250);
            return false;
        });
        $('.toolbarScrolling .leftArrow').click(function () {
            counter = counter < 1 ? 0 : counter - 1;
            var partMover = counter * 20;
            scrollThePanel(partMover);
            $('.ui-slider-handle').animate({
                left: partMover + '%'
            }, 250);
            return false;
        });
        var scrollbar = $(".scroll-bar").slider({
            animate: true,
            slide: function (event, ui) {
                if (scrollContent.width() > scrollPane.width()) {
                    scrollThePanel(ui.value);
                } else {
                    scrollPane.scrollLeft(0);
                }
            }
        });
        //append icon to handle
        var handleHelper = scrollbar.find(".ui-slider-handle").append("<span class='ui-icon ui-icon-grip-dotted-vertical'></span>").wrap("<div class='ui-handle-helper-parent'></div>").parent();
        //change overflow to hidden now that slider handles the scrolling
        scrollPane.css("overflow", "hidden");
        //size scrollbar and handle proportionally to scroll distance
        function sizeScrollbar() {
            var remainder = scrollContent.width() - scrollPane.width();
            var proportion = remainder / scrollContent.width();
            var handleSize = scrollPane.width() - (proportion * scrollPane.width());
        }
        //reset slider value based on scroll content position
        function resetValue() {
            var remainder = scrollPane.width() - scrollContent.width();
            var leftVal = scrollContent.css("margin-left") === "auto" ? 0 : parseInt(scrollContent.css("margin-left"));
            var percentage = Math.round(leftVal / remainder * 100);
            scrollbar.slider("value", percentage);
        }
        //if the slider is 100% and window gets larger, reveal content
        function reflowContent() {
            var showing = scrollContent.width() + parseInt(scrollContent.css("margin-left"), 10);
        }
        //change handle position on window resize
        jQuery(window).resize(function () {
            resetValue();
            //sizeScrollbar();
            reflowContent();
        });
        //init scrollbar size
        //setTimeout( sizeScrollbar, 10 );//safari wants a timeout
    }
};
app_etalage = (function () {
    function init(elem, time, props) {
        var length = $(elem).find('li').length,
            setToCurrent, curSlide = 0, positionArrows,
            listPadding = 0, calcWidthOnResize,
            timer = time * 1000 || 5000, repositionElements,
            oldCur = 0, fullWidth = props.fullWidth || false,
            widthIndicator = 0,
            widthSlides = 0;

        $(elem).css({
            overflow: 'visible'
        });
        prop = {};
        if (props === undefined) {
            prop.navigationArrows = true;
            prop.navigationList = true;
            prop.indicator = true;
            prop.width = $(window).width();
            prop.indicatorWidth = 80;
        } else {
            prop = props;
            prop.width = props.width || $(window).width();
            prop.hideArrows = props.hideArrows || false;
            prop.navigationArrowsOnList = props.navigationArrowsOnList || false;
        }
        $(elem).parent().append('<ol id="etalageModuleNav"></ol><div id="etalageIndicator"></div>');
        $(elem).wrap('<div id="etalageMask"></div>');
        
        calcWidthOnResize = function () {
            var curWidth = 0;
            return {
                setWidth: function (width, curSlide) {
                    curWidth = width * curSlide;
                },
                getWidth: function () {
                    return curWidth;
                }
            }
        };
        
        repositionElements = function () {
            prop.width = fullWidth ? $(window).width() : prop.width; 
            $(elem).find('li').each(function (i) {
                $(this).css({
                    left: (i * prop.width),
                    width: prop.width
                });
            });
            widthIndicator = $('#etalageIndicator').width();
            if (!$(elem).is(':animated')) {
                $(elem).css({left: -(curSlide * prop.width)});
                $(elem).width(length * prop.width);
            }
            positionArrows();
        };

        if (fullWidth) {
            $(window).resize(function (){
                repositionElements();
            });
        }
        
        
        setToCurrent = function (index) {
            var etalageElem = $(elem).find('li').eq(index);
            if (!prop.indicator) {
                restartNextSlide = function () {};
            }
            $('#etalageModuleNav li').removeClass('current');
            $('#etalageModuleNav li').eq(index).addClass('current');
            if (index >= length - 1) {
                $('.etalageNav_right').hide();
            } else {
                $('.etalageNav_right').show();
            }
            if (index <= 0) {
                $('.etalageNav_left').hide();
            } else {
                $('.etalageNav_left').show();
            }
            /**
             *Animate slide
             **/
            $(elem).stop().animate({
                left: -(index * prop.width)
            }, 1500, restartNextSlide);
        };
        if (prop.navigationList) {
            app_utils.mapArray(length, function (i) {
                var cur = i === 0 ? 'current' : '';
                $('#etalageModuleNav').append('<li class="etalage_btn_' + (i + 1) + ' ' + cur + '">' + (i + 1) + '</li>');
            });
            $('#etalageModuleNav li').click(function () {
                curSlide = $(this).index();
                stopIndicator();
                setToCurrent(curSlide);
            });
        }
        if (prop.navigationArrows) {
            $(elem).parent().append('<span class="etalageNav_left etalage_arrowNavigation" style="display: none;">&lt;</span><span class="etalageNav_right etalage_arrowNavigation">&gt;</span>');
            if (prop.navigationArrowsOnList) {
                listPadding = ($('#etalageModuleNav').length > 0) ? $('#etalageModuleNav').css('padding-left').replace('px', '') : 0;
                positionArrows = function () {
                    $('.etalageNav_left').css({
                    left: $('#etalageModuleNav').offset().left - $('.etalageNav_left').width()
                    });
                    $('.etalageNav_left, .etalageNav_right').css({
                        top: $('#etalageModuleNav').position().top
                    });
                    $('.etalageNav_right').css({
                        left: $('#etalageModuleNav').offset().left + ($('#etalageModuleNav').width() + (listPadding * 2))
                    });
                };
                
            }
            $('.etalageNav_left').click(function () {
                curSlide -= 1
                setToCurrent(curSlide);
                stopIndicator();
            });
            $('.etalageNav_right').click(function () {
                curSlide += 1
                setToCurrent(curSlide);
                stopIndicator();
            });
        }
        stopIndicator = function () {
            prop.indicator = false;
            $('div#etalageIndicator').stop();
            $('div#etalageIndicator').hide();
        };
        if (prop.indicator) {
            restartNextSlide = function () {
                $('div#etalageIndicator').width(0);
                $('div#etalageIndicator').animate({
                    width: prop.indicatorWidth
                }, timer, function () {
                    curSlide = curSlide >= length - 1 ? 0 : curSlide + 1;
                    setToCurrent(curSlide);
                    $('div#etalageIndicator').width(0);
                });
            }
            restartNextSlide();
        } else {
            $('div#etalageIndicator').hide();
        }
        
        repositionElements();
    }
    return {
        start: function (elem, time, prop) {
            if (elem.length > 0) {
                init(elem, time, prop);
            }
        }
    }
}());
app_modules = {
    sexyYoutube: function (vid, width, height) {
        vid.each(function () {
            var vids = $(this),
                curVidObj = vids.html(),
                openVideo;
            if (vids.find('iframe').length > 0) {
                vidCode = vids.find('iframe').attr('src').split('/')[4];
                isCustomImage = vids.attr('title').length > 0 ? vids.attr('title') : 'http://i4.ytimg.com/vi/' + vidCode + '/0.jpg';
                vids.attr('title', '');
                vids.html('<img src="' + isCustomImage + '" height="' + height + '" style="width: ' + width + 'px; height:' + height + ';"/><span class="playBtn"></span>');
                openVideo = function () {
                    createOwnPopUp.open({
                        prefix: '<div class="ownInfo">',
                        suffix: '</div>',
                        content: curVidObj
                    });
                    createOwnPopUp.setVideoProps(600, 450);
                };
                vids.click(function () {
                    openVideo();
                });
                $('.watchVideo').click(function () {
                    vids.trigger('click');
                    return false;
                });
            }
        });
    }
};
createOwnPopUp = {
    open: function (o) {
        var html = "<div id=\"ownPop\"><div class=\"ownOverlay\"></div><div class=\"ownContent\"></div></div>",
            _this = this;
        if ($('#ownPop').length < 1) {
            $('body').append(html);
            $('#ownPop').hide();
            $('#ownPop .ownContent').hide();
            $('#ownPop .ownContent').append('<div class="ownControllers"><a href="#">sluiten</a></div>');
            $('#ownPop .ownContent').append('<div class="ownContentHolder"></div>');
        }
        if (o.content !== undefined) {
            $('#ownPop .ownContent .ownContentHolder').html(o.prefix + o.content + o.suffix);
        }
        $('#ownPop .ownOverlay, #ownPop div.ownControllers a').click(function () {
            _this.close();
            return false;
        });
        $('#ownPop').fadeIn('slow', function () {
            $('#ownPop .ownContent').fadeIn('slow');
        });
        $(window).scroll(function () {
            var top = $(window).scrollTop() + ($(window).height() / 2);
            $('#ownPop .ownContent').css({
                top: top
            });
        });
        $('#ownPop .ownContent').css({
            top: $(window).scrollTop() + ($(window).height() / 2)
        });
    },
    close: function () {
        $('#ownPop .ownContent').fadeOut('slow', function () {
            $('#ownPop').fadeOut('slow', function () {
                $('#ownPop').remove();
            });
        });
    },
    setVideoProps: function (width, height) {
        $('#ownPop iframe').width(width);
        $('#ownPop iframe').height(height);
    }
};
app_utils = {
    mapArray: function (length, callback) {
        var i = 0;
        while (i < length) {
            callback(i);
            i += 1;
        }
    },
    objectMap: function (obj, callback) {
        var n;
        for (n in obj) {
            callback(n, obj[n]);
        }
    },
    disabled: function (dom) {
        dom.addClass('disabled').parent().addClass('disabledWrapper');
    },
    highlight: function (domEl, colorFrom, colorTo, howmany, border) {
        var counter, howManyTimes = howmany || 2,
            borderHighlight = border || false,
            highlightContainer;
        counter = function (times) {
            var count = 1;
            counter = function (times) {
                count += 1;
                return count > times - 1 ? true : false;
            }
        };
        highlightContainer = function () {
            var typeHighlightStart = borderHighlight ? {
                border: 'solid 1px ' + colorFrom
            } : {
                backgroundColor: colorFrom
            },
                typeHighlightStartEnd = borderHighlight ? {
                    border: 'solid 1px ' + colorTo
                } : {
                    backgroundColor: colorTo
                };
            domEl.css(typeHighlightStart);
            domEl.animate(typeHighlightStartEnd, 500, function () {
                if (!counter(howManyTimes)) {
                    highlightContainer();
                }
            });
        };
        highlightContainer();
    },
    getFormValues: function (form) {
        var values = {},
            checkboxes = {};
        form.find('input[type="checkbox"], input[type="radio"]').each(function () {
            values[$(this).attr('name')] = '';
        });
        form.find('input:checked').each(function () {
            values[$(this).attr('name')] = $(this).val();
        });
        form.find('select').each(function () {
            values[$(this).attr('name')] = $(this).val();
        });
        form.find('input[type="text"], input[type="password"], input[type="hidden"], textarea').each(function () {
            values[$(this).attr('name')] = $(this).val();
        });
        return values;
    },
    trimText: function (dom, length) {
        dom.each(function () {
            var _this = $(this),
                content = _this.text();
            if (_this.text().length > length) {
                _this.html(_this.text().substr(0, length) + '..');
                _this.easyTooltip({
                    xOffset: -60,
                    yOffset: -20,
                    content: content,
                    width: 150
                });
            }
        });
    },
    /*
     *
     * Get to Cookie information
     *
     * @param    cookieName: String - The name of the cookie
     * @return      The cookie information as a string
     *
     */
    getCookie: function (cookieName) {
        var x, y, cookiesArray = document.cookie.split(";"),
            cookieContent;
        this.mapArray(cookiesArray.length, function (i) {
            x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
            y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x === cookieName) {
                cookieContent = unescape(y);
            }
        });
        return cookieContent;
    },
    /*
     *
     * Test if cookie exists
     *
     * @param    cookieName: String - The name of the cookie
     * @return      Boolean
     *
     */
    cookieExist: function (cookieName) {
        var counter = 0;
        if (document.cookie !== "") {
            var cookiesArray = document.cookie.split(';');
            this.mapArray(cookiesArray.length, function (i) {
                var cookie = cookiesArray[i].split('=')[0];
                cookie = cookie.replace(/^\s+|\s+$/g, "");
                if (cookieName === cookie) {
                    counter += 1;
                }
            });
            return counter > 0 ? true : false;
        } else {
            return false;
        }
    },
    /*
     *
     * Edit the cookie information
     *
     * @param    cookieName: String - The name of the cookie
     * @param    value: String - New cookie value
     * @return      Nothing
     *
     */
    editCookie: function (cookieName, value) {
        if (document.cookie !== "") {
            var cookiesArray = document.cookie.split(';');
            this.mapArray(cookiesArray.length, function (i) {
                var cookie = cookiesArray[i].split('=')[0];
                cookie = cookie.replace(/^\s+|\s+$/g, "");
                if (cookieName === cookie) {
                    document.cookie = cookie + "=" + value;
                }
            });
        }
    },
    /*
     *
     * Delete the cookie
     *
     * @param    cookieName: String - The name of the cookie
     * @return      Nothing
     *
     */
    removeCookie: function (cookieName) {
        if (document.cookie !== "") {
            var cookiesArray = document.cookie.split(';'),
                expDate;
            expDate = new Date();
            expDate.setDate(expDate.getDate() - 1);
            this.mapArray(cookiesArray.length, function (i) {
                var cookie = cookiesArray[i].split('=')[0];
                if (cookieName === cookie) {
                    document.cookie = cookie + "=;path=/;expires=" + expDate.toGMTString();
                }
            });
        }
    },
    /*
     *
     * Test if an object is empty
     *
     * @param    obj: Object to test
     * @return      Boolean
     *
     */
    objectEmpty: function (obj) {
        var prop;
        for (prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                return false;
            }
        }
        return true;
    },
    /*
     *
     * Create a fresh cookie
     *
     * @param    cookieName: String - The name of the cookie
     * @param    value: String - New cookie value
     * @param    hours: Integer - Specify the experation date of a cookie in hours, default = (3600 * 1000)
     * @return      Nothing
     *
     */
    setCookie: function (cookieName, value, hours) {
        var exdate = new Date(),
            c_value, exdays = hours === undefined ? (3600 * 1000) : hours * (3600 * 1000);
        exdate.setTime(exdate.getTime() + exdays);
        c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = cookieName + "=" + c_value;
    },
    /*
     *
     * Inrement a integer by a specific number
     *
     * @param    int: A incrementing integer
     * @return    An auto incrementing integer
     *
     */
    incrementInt: (function (integ) {
        integ = integ || 0;
        return function () {
            var initData = integ += 1;
            return initData;
        };
    }(0)),
    /*
     *
     * Remove all whitespaces from string
     *
     * @param    str: A string to clean
     * @return    A new string cleaned from spaces
     *
     */
    clearAllSpaces: function (str) {
        return str.replace(/^\s+|\s+$/g, '');
    },
    /*
     *
     * Stringify a JSON object
     *
     * @param    object: Object
     * @return    String
     *
     */
    stringify: function (object) {
        return JSONstring.make(object);
    },
    /*
     *
     * Create a object from a string
     *
     * @param    stringData: String
     * @return    Object
     *
     */
    toObject: function (stringData) {
        return JSONstring.toObject(stringData);
    },
    toggleB: (function (toggler) {
        var toggleIt = toggler,
            toggle;
        return {
            toggle: function () {
                return toggleIt = !toggleIt;
            }
        };
    }(true))
};
$(function () {
    app_etalage.start($('ul#etalage'), 5, {
        navigationArrows: true,
        navigationList: true,
        navigationArrowsOnList: true,
        indicator: true,
        hideArrows: true,
        fullWidth: true,
        indicatorWidth: 480
    });
    if ($('div#shopPackages .content ul li').length > 4) {
        app_scrollBar.start({
            scrollPane: $('div#shopPackages .content'),
            scrollContent: $('div#shopPackages .content ul')
        });
    } else {
        $('div#shopPackages .content ul').width('100%');
    }
    app_layout.loader.create();
    app_interactive.loginBox.create();
    app_interactive.tooltips();
    app_modules.sexyYoutube($('.mini_video .vid'), 230, 130);
    app_interactive.shop();
    app_interactive.filterBox();
    app_interactive.fixedTools();
    app_interactive.assets();
    app_interactive.filterTool();
    app_interactive.form();
    app_interactive.tabbedForm($('#profilePage .contentHolder'), 'form');
    app_layout.products();
    app_layout.faq();
    app_layout.emaillink();
    
    /*$("body").bind("ajaxComplete", function(e, xhr, settings){
       app_interactive.shop();
    });*/

});
//
// ================= Attach handlers to the domObjects
//
(function ($) {
    $.fn.handleSubmit = (function () {
        var reqData, callBackAfterSubmitted, requestType = 'format/json/';
        callBackAfterSubmitted = function (callback) {
            var preCalled = callback;
            callBackAfterSubmitted = function (data) {
                if (typeof (preCalled) === 'function') {
                    preCalled(data);
                }
            }
        };
        return {
            onsubmit: function (data) {
                if (callBackAfterSubmitted !== undefined) {
                    callBackAfterSubmitted(data);
                }
            },
            setRequestType: function (type) {
                requestType = (type === 'json') ? 'format/json/' : '';
            },
            getRequestType: function () {
                return requestType;
            },
            submitted: function (callback) {
                callBackAfterSubmitted(callback);
            }
        }
    }());
}(jQuery));
(function (a) {
    a.fn.easyTooltip = function (b) {
        var c = {
            xOffset: 10,
            yOffset: 25,
            tooltipId: "easyTooltip",
            width: 300,
            clickRemove: false,
            content: "",
            useElement: ""
        },
            d;
        b = a.extend(c, b);
        this.each(function () {
            var c = a(this).attr("title");
            a(this).hover(function (e) {
                d = b.content !== "" ? b.content : c;
                d = b.useElement !== "" ? a("#" + b.useElement).html() : d;
                a(this).attr("title", "");
                if (d !== "" && d !== undefined) {
                    a("body").append('<div style="width:' + b.width + "px; \" id='" + b.tooltipId + "'>" + d + '<div class="tip"></div></div>');
                    a("#" + b.tooltipId).css("position", "absolute").css("top", e.pageY - b.yOffset + "px").css("left", e.pageX + b.xOffset + "px").css("display", "none").fadeIn("fast")
                }
            }, function () {
                a("#" + b.tooltipId).remove();
                a(this).attr("title", c)
            });
            a(this).live("mousemove", function (c) {
                a("#" + b.tooltipId).css("top", c.pageY - b.yOffset + "px").css("left", c.pageX + b.xOffset + "px")
            });
            if (b.clickRemove) {
                a(this).live("mousemove", function (d) {
                    a("#" + b.tooltipId).remove();
                    a(this).attr("title", c)
                })
            }
        })
    }
})(jQuery);

