

var jsonDataDir = 'data/';

var imgDir = '../images/';


jQuery.fn.encHTML = function() {
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    me.html(html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'));
  });
};
 
jQuery.fn.decHTML = function() {
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    me.html(html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
  });
};
 
jQuery.fn.isEncHTML = function(str) {
  if(str.search(/&amp;/g) != -1 || str.search(/&lt;/g) != -1 || str.search(/&gt;/g) != -1)
    return true;
  else
    return false;
};
 
jQuery.fn.decHTMLifEnc = function(){
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    if(jQuery.fn.isEncHTML(html))
      me.html(html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
  });
}



$(function () {



    $('input[data-placeholder],textarea[data-placeholder]').inputPlaceholder();



    // Facebook Like...

    $('a.facebook').click(function (e) {

        e.preventDefault();

        var url = 'http://www.facebook.com/sharer/sharer.php'

				+ '?u=' + encodeURIComponent(location.href)

				+ '&t=' + encodeURIComponent(document.title);

        window.open(url, 'sharer', 'toolbar=0,status=0,width=626,height=436');

    });



    // CV popups

    $('body').delegate('a.cvpopup', 'click', function (e) {

        e.preventDefault();

        $('body').addClass('fancybox-noclose');

        $.fancybox({

            type: 'iframe',

            href: $(this).attr('href'),

            orig: $(this),

            width: 750,

            height: 200,

            padding: 0,

            overlayColor: '#fff',

            overlayOpacity: 0.6,

            transitionIn: 'elastic',

            scrolling: 'no',

            onClosed: function () { $('body').removeClass('fancybox-noclose'); }

        });

    }).delegate('a.cvpopup', 'hover', function (e) {

        if (e.type == 'mouseenter') {

            $(this).find('img').stop().fadeTo(200, 0.8);

        } else {

            $(this).find('img').stop().fadeTo(200, 1);

        }

    });



    // Intro

    if ($('#intro').length > 0) {

        var currentIdx = 0;

        var totalIndexItems = $('#intro-menu>li').length;



        $('#intro-menu>li').each(function (i, e) {

            $(this).data('idx', i);

        }).append('<span/>').find('>a').click(function (e) {

            e.preventDefault();

            var idx = $(this).parent('li').data('idx');

            toggleToIntro(idx);

        });



        function toggleToIntro(idx) {

            $('#intro-content>li').hide().filter(':eq(' + idx + ')').show();

            $('#intro-menu>li').removeClass('active').filter(':eq(' + idx + ')').addClass('active');



            if ($('#intro-content-detail').hasClass('active')) {

                toggleToIntroDetail(idx);

            }



            currentIdx = idx;

        }



        $('#intro-content>li>div.block-visual')

			.append('<span class="__overlay"/>')

			.each(function (i) {

			    $(this).find('a').click(function (e) {

			        e.preventDefault();

			        toggleToIntroDetail(i);

			    });

			});



        function toggleToIntroDetail(idx) {

            $('#intro-content-detail>ul>li').hide().filter(':eq(' + idx + ')').show();

            $('#intro-content-detail').addClass('active');

        }



        function getNextIntroIdx() {

            return (currentIdx == totalIndexItems - 1) ? 0 : currentIdx + 1;

        }



        $('#intro-content-detail span.close').click(function () {

            $(this).closest('li').hide();

            $('#intro-content-detail').removeClass('active');

        });



        $('#intro-content-detail div.controls span.next').click(function () {

            toggleToIntro(getNextIntroIdx());

        });

    }



    // Add overlays to headers

    $('div.carroussel.heading>ul>li,#home-global').prepend('<span class="__overlay"/>');



    // Fondsen selector

    $('div.pallet-fondsen').each(function () {

        $(this).find('>ul>li a.fonds').click(function (e) {

            e.preventDefault();

            var fonds = $(this).closest('li');

            showFonds(fonds);

        });

    });



    function showFonds(fondsEle) {

        fondsEle.siblings('li').removeClass('active');

        fondsEle.addClass('active');

        var palletEle = fondsEle.closest('div.fondsenpallet');



        if (fondsEle.hasClass('intro')) {

            // Show toelichting

            resetBoutiekGraphs(palletEle.find('div.pallet-data'), palletEle);

            palletEle.find('div.pallet-data,div.pallet-team').hide();

            palletEle.append('<img src="' + fondsEle.data('visual') + '" class="fondstoelichting"/>')

        } else {

            var dataEle = palletEle.find('div.pallet-data').show();

            palletEle.find('div.pallet-team').show();

            var nodeId = fondsEle.data('graphdata');



            resetBoutiekGraphs(dataEle, palletEle);



            // Cache jsondata at element
            if (fondsEle.data('jsondata')) {

                initBoutiekGraphs(dataEle, fondsEle.data('jsondata'), true);

            } else {

                $.getJSON('httphandlers/FundInfo.ashx', { id: nodeId }, function (data) {

                    fondsEle.data('jsondata', data);

                    resetBoutiekGraphs(dataEle, palletEle);

                    initBoutiekGraphs(dataEle, data, false);

                });

            }

        }

    }

    function disclaimers() {
        var disclaimers;

    }


    function resetBoutiekGraphs(dataEle, palletEle) {

        palletEle.find('>img.fondstoelichting').remove();



        setRiskLevel(0);



        var ul = dataEle.find('>ul.yearperc');

        ul.find('li>span').each(function () {

            $(this).stop().css('width', 1).html('').show();

        });



        dataEle.find('div.date').html('');



        if (boutiekChart) {

            boutiekChart.destroy();

            boutiekChart = null;

        }



        var teamEle = palletEle.find('div.pallet-team');

        teamEle.removeClass('double').find('a.teamfocus').remove();



        var specEle = teamEle.find('div.specialisten');

        specEle.find('ul').remove();

    }



    var boutiekChart;



    function initBoutiekGraphs(dataEle, data, fromCache) {

        // Init / animate Ytd

        var ul = dataEle.find('>ul.yearperc');

        var max = 0;

        $.each(data.yearPercentages, function (i, val) {

            if (Math.abs(val) > max) max = Math.abs(val);

        });

        var p = 0;

        $.each(data.yearPercentages, function (i, val) {

            ul.find('>li:eq(' + p + ')').each(function () {

                $(this).find('>strong').html(i).end()

					.find('>span').html(val + '%')

					.toggleClass('negative', val < 0);



                if (val == 0) {

                    $(this).hide();

                } else {
                    $(this).show();
                    $(this).find('>span').animate({

                        width: (Math.abs(val) / max * 180)

                    }, 1000);

                }

            });


            p++;

        });



        // Init date
		if(data.date != null){
			dataEle.find('div.date').text(source + ' ' + data.date);
		}



        // Init team

        var teamEle = dataEle.closest('div.fondsenpallet').find('div.pallet-team');



        if (data.team.fondsmanager.length > 1) teamEle.addClass('double');

        for (var i = data.team.fondsmanager.length - 1; i > -1; i--) {

            var fmEle = $('<a href="" class="teamfocus cvpopup"><img src="" width="237" height="144" alt="" /><span><strong></strong> <span>\\ ' + data.team.fondsmanager[i].jobTitle + '</span></span></a>');

            fmEle.attr('href', data.team.fondsmanager[i].url)

						.find('img').attr('src', '/umbraco/imagegen.aspx?image=' + data.team.fondsmanager[i].img + '&width=237&height=144&crop=resize&antialias=true&compressionnr=100&format=jpg&align=middle&valign=middle').end()

						.find('strong').text(data.team.fondsmanager[i].name);

            teamEle.prepend(fmEle);

        }



        var teamUL = $('<ul/>');
        $('#spec').css('display', 'block');

        if (data.team.specialists.length == 0) {
            $('#spec').css('display', 'none');
        }

        for (var i = 0; i < data.team.specialists.length; i++) {

            var liEle = $('<li><a href="" class="cvpopup"><img src="" width="65" height="65" title="" /></a></li>');

            liEle.find('>a').attr('href', data.team.specialists[i].url)

						.find('>img').attr('src', '/umbraco/imagegen.aspx?image=' + data.team.specialists[i].img + '&width=65&height=65&crop=resize&antialias=true&compressionnr=100&format=jpg&align=center&valign=center')

						.attr('title', data.team.specialists[i].name);

            teamUL.append(liEle);

        }



        specEle = teamEle.find('div.specialisten');

        specEle.append(teamUL);



        // Set footer risk level

        setRiskLevel(data.risklevel);



        // Init HighChart

        var graphEle = dataEle.find('div.highchart');



        var chartConfig = HighChartsConfig.boutiek();

        chartConfig.chart.renderTo = graphEle[0];

        chartConfig.series[0].data = processBoetiekData(data.data);



        boutiekChart = new Highcharts.Chart(chartConfig);

    }





    // Kerngetallen tablinks

    $('ul#kerngetallen-data>li.clickable').click(function (e) {

        var tabid = $(this).data('tabid');

        var tab = $('ul.tabs>li[data-tabid=' + tabid + ']');

        showTab(tab, tabid);

    });



    // Kerngetallen fonds select

    $('#fonds-select>ul>li>a').click(function (e) {



        if ($(this).next('ul').length == 0)

            return this;



        e.preventDefault();

        var fsEle = $('#__fondsselector');

        if (fsEle.length == 0) {

            fsEle = $('<div id="__fondsselector"/>').appendTo('#kerngetallen');

        }



        fsEle.empty()

			.append($('<span class="close"/>').click(function () {

			    fsEle.hide();

			}))

			.append('<strong>' + $(this).text() + '</strong>')

			.append($(this).next('ul').clone(true));

        fsEle.show();

    });

    // Kerngetallen info
    $('#kerngetallen span.info').click(function () {
        var li = $(this).closest('li');
        li.find('div.info-content').show();
        if ($.browser.msie && $.browser.version < 8)
            li.css('z-index', 1);
    });
    $('#kerngetallen div.info-content span.close').click(function () {
        $(this).closest('div.info-content').hide();
        if ($.browser.msie && $.browser.version < 8)
            $(this).closest('li').css('z-index', 0);
    });

    // Homepage info
    $('.home-fonds-content span.info').click(function () {
        var div = $('.home-fonds-content div.info-content');
        div.show();
        if ($.browser.msie && $.browser.version < 8)
            div.css('z-index', 1);
    });
    $('.home-fonds-content div.info-content span.close').click(function () {
        $('.home-fonds-content div.info-content').hide();
        if ($.browser.msie && $.browser.version < 8)
            $('.home-fonds-content div.info-content').css('z-index', 0);
    });





    // Teamslider Fonds

    $('#teamslider').addClass('js').each(function () {

        var list = $(this).find('ul');

        var items = list.find('>li');



        if (items.length > 3) {

            var nav = $('<div class="__teamslidernav"></div>').appendTo(this).click(function () {

                list.animate({

                    marginLeft: '-=75'

                }, 300, 'swing', function () {

                    $(this).find('>li:first-child').remove().appendTo(this);

                    $(this).css('marginLeft', 0);

                });

            }).each(function () {

                this.onselectstart = this.onmousedown = function () { return false };

            });

        }



    });



    // Teamslider Over ons

    $('div.teamslider').addClass('js').each(function () {

        var list = $(this).find('ul');

        var items = list.find('>li');

        var animating = false;



        if (items.length > 4) {

            $('<div class="__teamslidernav_prev"></div>').appendTo(this).click(function () {

                if (animating) return;

                animating = true;

                list.find('>li:last-child').remove().prependTo(list);

                list.css('marginLeft', -200);

                list.animate({

                    marginLeft: '+=200'

                }, 300, 'swing', function () {

                    animating = false;

                });

            }).each(function () {

                this.onselectstart = this.onmousedown = function () { return false };

            });



            $('<div class="__teamslidernav_next"></div>').appendTo(this).click(function () {

                if (animating) return;

                animating = true;

                list.animate({

                    marginLeft: '-=200'

                }, 300, 'swing', function () {

                    $(this).find('>li:first-child').remove().appendTo(this);

                    $(this).css('marginLeft', 0);

                    animating = false;

                });

            }).each(function () {

                this.onselectstart = this.onmousedown = function () { return false };

            });

        }

    });



    $('div.teams div.teamslider:not(:first)').hide();

    $('#teamselect').each(function () {

        var items = $(this).find('>li');

        items.each(function (i) {

            $(this).find('a').click(function (e) {

                e.preventDefault();

                $('div.teams div.teamslider').hide().filter(':eq(' + i + ')').show();

                items.removeClass('active');

                $(this).parent('li').addClass('active');

            });

        });

    });



    // Carroussel

    function initCarroussel(ele) {

        $(ele).each(function () {

            var items = $(this).find('>ul>li');

            if (items.length < 2) return this;



            var currentIndex = 0;

            var timer;

            var nav = $('<div class="__carrousselnav"></div>').appendTo(this);

            var animating = false;



            for (var i = 0; i < items.length; i++) {

                nav.append('<span>' + (i + 1) + '</span>');

            }

            nav.find('span').each(function (i) {

                $(this).data('idx', i);

                if (i == 0) $(this).addClass('active');

            }).click(function () {

                switchTo($(this).data('idx'));

            });



            if ($(this).hasClass('company-slideshow')) {

                $('<div class="__buttonprev"/>').click(function () {

                    switchTo(getPrevIndex());

                }).appendTo(this);

                $('<div class="__buttonnext"/>').click(function () {

                    switchTo(getNextIndex());

                }).appendTo(this);

            }



            function getPrevIndex() {

                return (currentIndex == 0) ? items.length - 1 : currentIndex - 1;

            }



            function getNextIndex() {

                return (currentIndex == items.length - 1) ? 0 : currentIndex + 1;

            }



            function switchTo(idx) {

                if (animating || idx == currentIndex) return;

                animating = true;

                var itemOld = $(items[currentIndex]);

                var itemNew = $(items[idx]);



                itemNew.css('zIndex', 5).show();

                itemOld.css('zIndex', 6).animate({

                    left: '-=50',

                    opacity: 0

                }, function () {

                    $(this).css({

                        left: 0,

                        display: 'none',

                        opacity: 1

                    });

                    animating = false;

                    resetTimer();

                });



                currentIndex = idx;

                nav.find('span').removeClass('active').filter(':eq(' + idx + ')').addClass('active');

            }



            function resetTimer() {

                clearInterval(timer);

                timer = setInterval(function () {

                    switchTo(getNextIndex());

                }, 90000);

            }



            function stopTimer() {

                clearInterval(timer);

            }



            if ($(this).hasClass('autoplay'))

                resetTimer();



        });

    }



    initCarroussel($('div.carroussel'));



    // Overzicht carrousel links2tab

    $('#tab-overzicht div.carroussel a').click(function (e) {

        if ($(this).attr('href') == '') {

            e.preventDefault();

            var tabid = 'tab-strategie';

            var tab = $('ul.tabs>li[data-tabid=' + tabid + ']');

            showTab(tab, tabid);

        }

    });



    // Company slider/selector

    $('div.company-list').each(function () {

        $(this).find('a').click(function (e) {

            e.preventDefault();



            var companyList = $(this).closest('div.company-list');

            var slider = companyList.prev('div.company-slideshow');



            var li = $(this).parent();



            var companyID = $(this).data('companyId');

            var companyCult = $(this).data('company-cult');



            companyList.find('li.active').removeClass('active');

            li.addClass('active');



            $.getJSON('httphandlers/CompanyInfo.ashx', { id: companyID, cult: companyCult }, function (data) {

                var title = $('<strong></strong>').text(data.title);

                var ul = $('<ul></ul>');

                for (var i = 0; i < data.slides.length; i++) {

                    if (data.slides[i].img != null) {

                        var li = $('<li><img src="" width="369" height="269" /><div></div></li>');

                        var alt = data.title + ' ' + (i + 1) + '/' + data.slides.length;

                        li.find('img').attr({

                            src: '/umbraco/imagegen.aspx?image=' + data.slides[i].img + '&width=369&height=269&antialias=true&compressionnr=100&format=jpg',

                            alt: alt,

                            title: alt

                        });

                        li.find('div').append($(data.slides[i].text));

                        ul.append(li);

                    }

                    else {

                        var li = $('<li><div class="text-only"></div></li>');

                        li.find('div').append($(data.slides[i].text));

                        ul.append(li);

                    }

                }

                slider.find('>strong,>ul,>div.__carrousselnav,>div.__buttonprev,>div.__buttonnext').remove();

                slider.append(title).append(ul);

                initCarroussel(slider);

            });



        });

    }).find('li.active>a').triggerHandler('click');



    // News slideout

    $('div.morenews').hide();

    $('div.morenews-trigger>a').click(function (e) {

        e.preventDefault();

        if ($(this).hasClass('close')) {

            $(this).parent().prev('div.morenews').stop().slideUp(200);

            $(this).text($(this).data('originalText'));

            $(this).removeClass('close');

        } else {

            $(this).parent().prev('div.morenews').stop().slideDown(200);

            $(this).data('originalText', $(this).text());

            $(this).text($(this).data('closeText'));

            $(this).addClass('close');

        }

    });





    // Tabs (keep after tabcontent definitions)

    $('ul.tabs>li').find('>a').click(function (e) {

        e.preventDefault();

        var tab = $(this).closest('li');

        showTab(tab, tab.data('tabid'));

    }).end().filter('.active').find('>a').each(function () {

        $(this).triggerHandler('click');

    });



    function showTab(tab, tabid) {

        tab.siblings('li').removeClass('active');

        tab.addClass('active');



        var tabcontent = $('#' + tabid);

        tabcontent.siblings('.tabcontent').removeClass('active');

        tabcontent.addClass('active');

		if(tab.data('disclaimerid') != undefined){
			$('#footer-text').html(window.siteconfig.disclaimers[tab.data('disclaimerid')]);

			$('#footer-text').decHTML();
		}

        // Boetiek tabs (fondsenpallet)

        if (tabcontent.hasClass('fondsenpallet')) {

            tabcontent.find('div.pallet-fondsen>ul>li.active a.fonds').triggerHandler('click');
        }



        // Fonds tabs

        if (tabcontent.hasClass('with-sidebar')) {

            $('#tab-sidebar').show();

        } else {

            $('#tab-sidebar').hide();

        }



        // Factsheet

        if (tabcontent.hasClass('factsheet')) {

            var hsEle = $('#highstock');

            if (hsEle.hasClass('complete')) return;

            hsEle.addClass('complete');

            var isin = hsEle.data('isin');



            $.getJSON('httphandlers/WebService.ashx', { action: "historynavs", ISIN: isin }, function (data) {

                var highstock = new Highcharts.StockChart({

                    chart: {

                        renderTo: 'highstock',

                        backgroundColor: null

                    },

                    credits: {

                        enabled: false

                    },

                    rangeSelector: {

                        selected: 1

                    },

                    xAxis: {

                        maxZoom: 14 * 24 * 3600000 // fourteen days

                    },

                    series: [{

                        data: data,

                        tooltip: {

                            yDecimals: 2,

                            xDateFormat: '%A, %b %e, %Y'

                        }

                    }]

                });

            });

        }



    }


    // Login

    $('#login').click(function (e) {

        e.preventDefault();

        $('#menu-login').toggle();

        if ($.browser.msie && $.browser.version < 8)

            $('#header').css('z-index', $('#menu-login').is(':visible') ? 99 : 0);

    });

    $('#menu-login span.close').click(function () {

        $('#menu-login').hide();

        if ($.browser.msie && $.browser.version < 8)

            $('#header').css('z-index', $('#menu-login').is(':visible') ? 99 : 0);

    });



    // Factsheet rendement

    $('div.fact-rendement').each(function () {

        var items = $(this).find('li>div');

        var max = 0;

        items.each(function () {

            var val = parseFloat($(this).data('val'));

            $(this).addClass(val >= 0 ? 'pos' : 'neg');

            if (Math.abs(val) > max) max = Math.abs(val);

        }).each(function () {

            var val = parseFloat($(this).data('val'));

            var h = ((Math.abs(val) / max) * 40) + 11;

            $(this).height(h);

        });

    });



    // Factsheet dividend info

    $('div.fact-dividend span.info').click(function () {

        $(this).closest('li').addClass('info');

    });

    $('div.fact-dividend span.close').click(function () {

        $(this).closest('li').removeClass('info');

    });





    // Meer content..

    $('div.more-content').each(function () {

        var div = $(this);

        $(this).find('span.showmore,a.button').click(function (e) {

            e.preventDefault();

            div.toggleClass('active');

        });

    });



    if ($('#funds-overview').length > 0) {

        $('a.open-type-detail').click(function (e) {

            e.preventDefault();

            var typeItem = $(this).parent();

            $('.type-detail', typeItem).slideDown();

        });



        $('.type-detail').each(function () {

            $('.close', this).click(function (e) {

                $(this).parents('.type-detail').slideUp();

            });

        });



    }



    if ($('#search-results-page').length > 0) {

        $('a.show-all').click(function (e) {

            e.preventDefault();

            var parentItem = $(this).parent();

            $(this).hide();

            $('ul', parentItem).show();

        });

    }



    // Home fonds selector..

    $('select.custom-select').each(function () {

        $(this).change(function () {

            $(this).parent('div').find('div.home-fonds-content').hide();

            $('#' + $(this).val()).show();

        }).triggerHandler('change');

    });



    // Nieuwsbrief lightbox

    $('#newsletter').click(function (e) {

        e.preventDefault();

        $.fancybox({

            type: 'iframe',

            href: $(this).attr('href'),

            orig: $(this),

            width: 570,

            height: 500,

            padding: 10,

            overlayColor: '#fff',

            overlayOpacity: 0.6,

            transitionIn: 'elastic'

        });

    });



});



function setRiskLevel(n) {

    $('#bijsluiter').removeClass('nivo0 nivo1 nivo2 nivo3 nivo4 nivo5').addClass('nivo' + n);

}



$.fn.inputPlaceholder = function () {

    return this.each(function () {

        if ($(this).val() == '' || $(this).val() == $(this).attr('data-placeholder')) {

            $(this).val($(this).attr('data-placeholder'))

				.addClass('init');

        }

        $(this).focus(function () {

            if ($(this).val() == $(this).attr('data-placeholder'))

                $(this).val('').removeClass('init');

        }).blur(function () {

            if ($(this).val() == '') {

                $(this).val($(this).attr('data-placeholder'))

					.addClass('init');

            }

        });

    });

};
