$(document).ready(function () {

    $('body').addClass('js');

    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        }
    }

    // Agenda click regions
    $('ul.agenda>li').click(function () {
        location.href = $(this).find('>strong>a').attr('href');
    });

    //Routeplanner
    if ($('#routeplanner-widget').length != 0) {
        var rr = $('.routeResult');
        rr.removeClass('hidden').hide();
        var zipField = $('#routeplanner-widget-postcode');
        var zipTo = $('#routeplanner-widget-locatie').val();
        $('#routeplanner-widget-submit').click(function (event) {
            var zipFrom = $(zipField).val();
            calcRouteMinutes(zipFrom, zipTo);
            return false;
        });
        $(zipField).keydown(function (event) {
            if (event.keyCode == '13') {
                event.preventDefault();
            }
        });
        $(zipField).keyup(function (event) {
            if (event.keyCode == '13') {
                var zipFrom = $(zipField).val();
                calcRouteMinutes(zipFrom, zipTo);
            }
        });
        $('#routeplanner-widget .change-zip').click(function (event) {
            resetRouteMinutes();
            return false;
        });
    }

    if ($('#routeplanner').length != 0) {
        var rr = $('.routeResult');
        rr.removeClass('hidden').hide();
        var zipField = $('#routeplanner-postcode');
        $('#routeplanner-submit').click(function () {
            var zipFrom = $(zipField).val();
            getRouteData(zipFrom);
            $("#9292ovLink").show();
            return false;
        });
        $(zipField).keydown(function (event) {
            if (event.keyCode == '13') {
                event.preventDefault();
            }
        });
        $(zipField).keyup(function (event) {
            if (event.keyCode == '13') {
                var zipFrom = $(zipField).val();
                getRouteData(zipFrom);
                $("#9292ovLink").show();
            }
        });
    }


    $(".educations #trainingOverview .training ul li").click(function () {
        //alert("hr");
        if ($(this).find("a:first").is('*')) var link = $(this).find("a:first").attr('href');
        window.location = link;
        return false;
    });

    //    $("#viewChanger .view a").live('click', function (e) {
    //        e.preventDefault();
    //        var url = $(this).attr("href");
    //        $("#trainingOverviewContainerHolder").load(url + " #trainingOverviewContainer", function () {
    //            cufonize();
    //        });
    //    });


    if ($('.ik-weet-het-echt-niet-meer').is('*')) {
        $('.ik-weet-het-echt-niet-meer').hover(function (e) {
            // console.log('hover')
            $(this).animatte({ 'backgroundPosition': '0% 100%' }, 500)
            e.preventDefault();
        }, function (e) {
            // console.log('hover out')
            $(this).animatte({ 'backgroundPosition': '0% 0%' }, 500)
            e.preventDefault();
        })
    }

    $(window).load(function () {
        $('div.actueel-slider').each(function () {
            var items = $(this).find('>ul>li');
            if (items.length <= 1) return this;
            var currentIndex = 0;
            var animating = false;

            $('<span class="__navprev"></span>').mousedown(function () {
                switchTo(getPrevIndex(), true);
                $(this).addClass('pressed');
                this.onselectstart = this.onmousedown = function () { return false };
            }).mouseup(function () {
                $(this).removeClass('pressed');
            }).appendTo(this);

            $('<span class="__navnext"></span>').mousedown(function () {
                switchTo(getNextIndex());
                $(this).addClass('pressed');
                this.onselectstart = this.onmousedown = function () { return false };
            }).mouseup(function () {
                $(this).removeClass('pressed');
            }).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, prev) {
                if (animating || idx == currentIndex) return;
                animating = true;
                var itemOld = $(items[currentIndex]);
                var itemNew = $(items[idx]);

                itemNew.css('left', prev ? -390 : 390).show()
					.add(itemOld).animate({
					    left: prev ? '+=390' : '-=390'
					}, 300, function () {
					    animating = false;
					});

                currentIndex = idx;
            }
        });

    });

    $('ul.beroepen').ttCollapse({
        openText: "Meer beroepen",
        closeText: "Minder beroepen"
    });


    /*$('ul.beroepen').after('<a href="#" class="elementToggle">Meer beroepen</a>')
    $('ul.beroepen').next().click(function () {

    $('ul.beroepen').toggle(function () {
    alert("toggle 1")
    $(this).next().text('Minder beroepen')
    $($(this) + '> *').filter(":hidden").show();
    }, function () {
    alert('toggle 2')
    $(this).next().text('Meer beroepen')
    $($(this) + '> *').filter(":gt(3)").hide();
    });

    return false;
    });*/

    if ($('html > .showcases').length) {
        $.getScript('/scripts/jquery.showcases.js', function () {
            showcase_init();
        });
    }

    if ($('html > .research, html > .lectors, html > .publications').length) {
        $.getScript('/scripts/jquery.research.scripts.js', function () {
            research_init();
        });

    }

    animateMenu('#mainMenu li');
    animateMenu('#metaMenu li.share');
    formSelected();

    changeSelect();

    changeSelectContact();

    initFilter();
    filterSelect();
    displayTooltips();

    //mediaTargetedScript();
    //replaceTotalResults();

    initSpecialLinks();
    initViewSwitch();
    slider();

    initPanorama();
    Shadowbox.init();

    setupInlineTabsHandler();

    //Twitter triangle fix
    $("<span class=\"triangle\"></span>").insertAfter("#twitter_update_list li span");

    cufonize();

    loadWatermarks();
});

function resetRouteMinutes() {
    sr = $('.searchRoute');
    $(sr).find('h2').html('Check je reistijd');
    var rr = $('.routeResult');
    $(rr).fadeOut(500, function () {
        $(sr).fadeIn(500)
    });
    Cufon.refresh();
    return false;
}

function calcRouteMinutes(zipFrom, zipTo) {
    zipTo = zipTo.replace(' ', '');
    sr = $('.searchRoute');
    var pi = '<img class="loader" src="/images/ajax-loader3.gif" />'
    $(sr).find('fieldset').append(pi);
    $.getJSON('/handlers/ov9292.ashx/?action=calcminutes&zipfrom=' + zipFrom + '&zipto=' + zipTo, function (data) {
        $(sr).find('.loader').remove();
        if (data > 0) {
            var rr = $('.routeResult');
            $(rr).find('h2').html('Je bent maar <strong>' + data + ' minuten</strong> onderweg!');
            var link = $(rr).find('a.more-info');
            var href = $(link).attr('href');
            href = href.split('?')[0] + '?pc=' + zipFrom;
            $(link).attr('href', href);
            //if good result switch divs
            $(sr).fadeOut(500, function () {
                $(rr).fadeIn(500)
            });
        }
        else if (data == -4004) {
            $(sr).find('h2').html('De postcode ligt op loopsafstand');
        }
        else {
            $(sr).find('h2').html('Route kon niet berekend worden');
        }
        Cufon.refresh();
        return false;
    });
}

function getRouteData(zipTo) {
    zipTo = zipTo.replace(' ', '');
    $('#routeplanner').addClass('foldout');
    var wrapper = $('#routeplanner-wrapper');
    if (wrapper == null || wrapper.length==0) {
        wrapper = $('<div id="routeplanner-wrapper" ></div>');
        $('#routeplanner-results').wrapAll(wrapper);
        wrapper = $('#routeplanner-wrapper');
    }

    if ($('#routeplanner .loader').length <= 0) {
        var pi = '<img class="loader" src="/images/ajax-loader3.gif" />';
        $('#routeplanner fieldset').append(pi)
    }
    $(wrapper).load(document.location.pathname + '/?pc=' + zipTo + ' #routeplanner-results', function () {
        $('#routeplanner .loader').remove();
    });
}

function loadWatermarks() {
    $('input[type=text]').addClass('watermarked').focus(function () {
        var t = $(this);
        if (t.attr('rel') == undefined) t.attr('rel', t.val())
        if (t.val() == t.attr('rel')) t.val('');
        t.removeClass('watermarked');
    }).blur(function () {
        var t = $(this);

        if (t.val() == '' || t.val() == t.attr('rel')) {
            t.val(t.attr('rel'));
            t.addClass('watermarked')//.addClass('routeError');
        }
    })
}

function setupInlineTabsHandler() {
    $('div.inlineTabs li a').click(function () { loadTab($(this)); return false; });
}

function loadTab(tab) {
    var url = tab.attr('href');
    var tabsElm = tab.parents('div#inlineTabsHolder')[0];
    $(tabsElm).load(url + ' div#inlineTabs', function () {
        setupInlineTabsHandler();
    });
}

function initViewSwitch() {
    var vs = $('#viewSwitch');
    vs.find('a').click(function () { switchView($(this)); });
}


function initSpecialLinks() {
    $('.pdf,.external').click(function (item) { window.open($(this).attr('href')); return false; });
}

function cufonize() {
    /* removeSpaces('#sidebar h2, #content h1, #subject h3, #facebook_home h3, #tweet_home h3, #content_home h1, #content h2, #facebook_home h4, #tweet_home h4, .training h2, #sidebar h3, .tooltip h3, .opleiding_block h2, .landing h1');
    removeSpaces('#sidebar h2 span, #content h1 span, #subject h3 span, #tweet_home h3 span, #facebook_home h3 span, .training h2 span, #subNav .subNavHead, .sidebarOpendag span, .selectOptions h3');
    removeSpaces('.landingBlock h2');
    removeSpaces('.opleidingTitle p');
    */


    /* firstWord('#sidebar h2, #content h1, #subject h3, #facebook_home h3, #tweet_home h3, .training h2, .landing h1, .landing h2 , .landingBlock h3');
    -IE7 can't handle this first word partial cufon light/bold thing, everything bold now*/


    /*Cufon standerd styles*/
    Cufon.replace(['h1, h2.titleLanding, .lectoren h2, #routeLocatie h4, #contactInfo h3'/*,h3:not(.programTitle)*/], {
        fontFamily: 'Interstate-Bold'
    });

    Cufon.replace(['h2:not(h2.accordion, h2.titleLanding, .lectoren h2, .rewardPeople h2, .agenda-filter h2), #sidebar h3, h4:not(h4.accordion, #beroepsfilter h4, .calendarOverview li h4, #routeLocatie h4)'], {
        fontFamily: 'Interstate-Light'
    });

    /*Cufon extra styles*/
    Cufon.replace(['.opleidingTitle p, #Title, .Title_opleiding h1, .play_btn span, .showcase_btn span, div.rewardPeople span.subtitle'], {
        trim: 'advanced', hover: true, fontFamily: 'Reklame Script Regular'
    });

    Cufon.replace(['.landingBlock .title'], {
        trim: 'advanced', hover: true, fontFamily: 'Interstate-LightItalic'
    });

    Cufon.replace(['.landingBlock h2:not(h2.accordion, h2.titleLanding, .lectoren h2)'], {
        trim: 'advanced', hover: true, fontFamily: 'Interstate-Regular'
    });

    /*Cufon exceptions*/
    Cufon.replace(['#sidebar h2, .calendarOverview h3'], {
        fontFamily: 'Interstate-Bold'
    });
    Cufon.replace(['#sidebar h3'], {
        fontFamily: 'Interstate-Light'
    });
    Cufon.replace(['.stagetube .programCluster h2 span'], {
        fontFamily: 'Interstate-Light'
    });



    /* Cufon.replace(['#sidebar h2, #content h1, #content h1, #subject h3, #facebook_home h3, #tweet_home h3, .training h2, #content h2, #sidebar h3, .landing h1, .landing h2, .landingBlock h3, #facebook_home h4, #tweet_home h4, .landingBlock h4'], {
    trim: 'advanced',
    hover: true,
    fontFamily: 'Interstate-Bold' // used to be light
    });
    Cufon.replace(['#sidebar h2 span, #content h1 span, #content:not(".home") h3, #subject h3 span, #facebook_home h3 span, #tweet_home h3 span, .training h2 span, .landing h1 span, .training h2, #subNav .subNavHead, .sidebarOpendag span, .opleiding_block h2, .selectOptions h3, .landingBlock h3 span, .sidebarShowcase h3,  .tooltip h3, .newsOverview h3 a, .newsOverview h3 a:hover, #routeLocatie h3, #opleidingenLocatie h3, .book h3, .carousel_item h1'], {
        
    fontFamily: 'Interstate-Bold'
    });
   
    
    */
}

var PauseC; //pause carousel variable;

function animateMenu(element) {
    /*$(element).attr('rel',$(element).find('.foldoutMenu').height());*/
    $(element).hover(function () {
        if ($(this).attr('rel') == null) $(this).attr('rel', $(this).find('.foldoutMenu').height());
        var n = Number($(this).attr('rel'));

        $(this).find('.foldoutMenu').animate({ height: n + 5 }, 1000);
        if ($(this).parent().hasClass('.foldoutMenu')) { $(this).addClass('hover'); }
    }, function () {
        var n = Number($(this).attr('rel'));
        //var currentHeight = $(this).find('.foldoutMenu').height();
        $(this).find('.foldoutMenu').height(n - 5);
        $(this).removeClass('hover');
    });
}

function firstWord(element) {
    $(element).each(function () {
        /*var arr = $(this).html().split(' ');
        arr[0] = '<span>'+arr[0]+'</span>';
        $(this).html(arr.join(' '));*/
        $(this).html($(this).html().trim().replace(/(^\w+)/, '<span>$1</span>'));
    });
}

function removeSpaces(element) {
    $(element).each(function () {
        $(this).html($(this).html().trim());
    });
}
// gives inputfields, selectfields, textareas blue borders when they are selected
function formSelected() {

    $('#questionForm select, #questionForm textarea, #questionForm input, .contactInfo select').focus(function () {
        if ($(this).hasClass('active')) {
            $('#questionForm select, #questionForm textarea, #questionForm input, .contactInfo select').removeClass('active');
        }

        $('#questionForm select, #questionForm textarea, #questionForm input, .contactInfo select').removeClass('active');
        $(this).addClass('active');

    });
}
// dropdown question subject
function changeSelect() {
    //Hide the fallback postback button
    $("div.question input.ddlCatsFallbackButton").hide();
}

// dropdown contactinfo 
function changeSelectContact() {
    $("div.contactDetail").hide();
    $("select#contactSelect").change(function () {
        var currentSelected = $("select#contactSelect option:selected").attr('class');
        $("div.contactDetail").hide();
        $("div." + currentSelected).fadeIn(300);
    });
}


// filter

function initFilter() {
    /*$('#f_richting').val('');
    $('#f_type').val('');*/

    $('#beroepsfilter').hide();

    initFoldOutAppeal();

    initFilterViewSwitch();

    $('.educations .filter_view_1').click(); /*force detail view*/


    $(".educations ul#filter li, p a.opleiding").each(function (i, item) { if ($(item).html() == '') { $(item).hide(); } });

    //    $("#selectedFilters .level").find("a").click(function () { unselectFilter($(this)); });
    //    $("#selectedFilters .category").find("a").click(function () { unselectFilter($(this)); });
    checkAppealsFoldoutHeaders();
    //$("ul#filter li.study").fadeIn();
}

function initFilterViewSwitch() {
    $('.educations .filter_view_2').click(function e() {

        $('#trainingResults').fadeOut(400, function () {
            $('#trainingOverview').addClass('listView');
            $(this).fadeIn(400);
        })

        $('.filter_view_2').addClass('active2');
        $('.filter_view_1').removeClass('active1');

        return false;
    });
    $('.educations .filter_view_1').click(function e() {
        $('#trainingResults').fadeOut(400, function () {
            $('#trainingOverview').removeClass('listView');
            $(this).fadeIn(400);
        })

        $('.filter_view_1').addClass('active1');
        $('.filter_view_2').removeClass('active2');

        return false;
    });
}

function filterSelect() {

//    $("#study a, p a.opleiding").click(function (e) {
//    
//        $("#study li, p a.opleiding").show();
//        $(this).parent().hide();

//        $("#selectedFilters .study, p a.opleiding").hide().html($(this).html()).fadeIn();
//        $("li.appeal").html('').hide();

//        loadEducations();
//    });

    $(".educations #f_type").each(function () {
        $(this).change(function (e) {
            loadEducations();
        });// [0].selectedIndex = 0;
    });

    $(".educations #f_richting").each(function () {
        $(this).change(function (e) {
            loadEducations();
        });// [0].selectedIndex = 0;
    });

    $('.educations #formTabs li a').click(function (e) {
        $('#formTabs li').removeClass('selected');
        $(this).parent().addClass('selected');
        loadEducations();
    });

    // [ create selected filter ] //

    $(".educations #appeal a, .educations .foldOutAppealColumn li a").click(function (e) {
       
        if ($(this).parent().hasClass('disabled') != true) {
            $("ul#filter li.appeal").show();
            var element = $(this).parent().hide(); // geklikte <LI> bewaren om straks weer terug te zetten
            var newElement = $("<li>" + $(this).html() + " <a>x</a></li>").fadeIn(); // nieuwe <LI> maken om in selectedFilter te gooien
            newElement.find("a").click(function () { // click event voor <a>x</a> in de nieuwe <li>
                element.fadeIn(); // en origineel tonen
                $(this).parent().remove(); // weg halen            
                loadEducations();
                checkSelectedEducation();
            });
            closeFoldOutAppeals($('a.filter_beroep'));
            var ul = createOrReturnUl(); // functie zie hieronder
            ul.append(newElement); // nieuwe <li> toevoegen aan de lijst
            loadEducations();
            checkSelectedEducation();
        } else {
            return false;

        }
    });

    $(".showcases #appeal a, .showcases .foldOutAppealColumn li a").click(function (e) {

        if ($(this).parent().hasClass('disabled') != true) {
            $("ul#filter li.appeal").show();

            var element = $(this).parent().hide(); // geklikte <LI> bewaren om straks weer terug te zetten
            var newElement = $("<li>" + $(this).html() + " <a rel='" + $(this).attr('rel') + "'>x</a></li>").fadeIn(); // nieuwe <LI> maken om in selectedFilter te gooien
            newElement.find("a").click(function () { // click event voor <a>x</a> in de nieuwe <li>
                element.fadeIn(); // en origineel tonen
                $(this).parent().remove(); // weg halen            

                window.sc_op = window.sc_op.replace($(this).attr('rel') + ',', '');
                checkSelectedEducation();
                requestData('replace');
            });
            closeFoldOutAppeals($('a.filter_beroep'));
            var ul = createOrReturnUl(); // functie zie hieronder
            ul.append(newElement); // nieuwe <li> toevoegen aan de lijst

            window.sc_op += $(this).attr('rel') + ",";

            requestData('replace');

        } else {
            return false;

        }

    });

    function createOrReturnUl() {
        var ul = $("#selectedFilters .appeal").find("ul"); // ul selecteren in de li.appeal
        if (ul.length != 1) { // niet gevonden?
            // ul toevoegen
            $("#selectedFilters .appeal").append("<ul></ul>"); // bouwen en in var ul stoppen
            ul = $("#selectedFilters .appeal").find("ul");
        }
        return ul; // gebouwt of al gevonden, return!
    }
}

function initFoldOutAppeal() {
    //    $(".moreAppeal").click(function (e) { openFoldOutAppeals(); });
    //    $("a#closeFoldOut").click(function (e) { closeFoldOutAppeals(); });

    //    $('.filterList, #foldOutAppeal').localScroll({
    //        easing: 'easeInQuad',
    //        duration: 500
    //    });

    if ($('.filter_beroep').length != 0) {
        $('.filter_beroep').click(function (e) {

            if ($('#beroepsfilter').hasClass('filter_beroep_selected') == false) {
                openFoldOutAppeals($(this));
                $("#selectedFilters").show();
                $(".page_filter .filter_nav_main").addClass("selectedFilter");
            } else {
                closeFoldOutAppeals($(this));
                checkSelectedEducation();
            }
            e.preventDefault();
        });

        $('.filter_alphabet').localScroll({
            target: '.filter_overview',
            axis: 'x'
        });

        $('.filter_alphabet a').addClass('disabled');
        $.each($('#beroepsfilter h4'), function () {
            var letter = '#' + $(this).text();

            $.each($('.filter_alphabet a'), function () {
                var nLetter = $(this).attr('href').toString();

                //console.log(letter +" -=-"+ nLetter)

                if (letter == nLetter) {
                    $(this).removeClass('disabled');
                } else {
                    $(this).click(function () { return false; })
                }
            });
        })
    }
}
function checkSelectedEducation() {
    // Check selectedFilter
    if ($("#selectedFilters li ul li").length > 0) {
        $("#selectedFilters").show();
        $(".page_filter .filter_nav_main").addClass("selectedFilter");
    } else {
        $("#selectedFilters").hide();
        $(".page_filter .filter_nav_main").removeClass("selectedFilter");
    }
}

function openFoldOutAppeals(buttonElm) {
//    $("#foldOutAppeal").slideDown(2000); /* Slide Down */
//    var btn = $('.moreAppeal');
//    btn.unbind();
//    btn.attr('class', 'lessAppeal');
//    btn.attr('href', '#scrollMore');
//    btn.text('Minder beroepen');
//    btn.click(function (e) { closeFoldOutAppeals(); });
//    $('div.foldOut').localScroll({
//        easing: 'easeInQuad',
//        duration: 500
    //    });
    $(buttonElm).addClass('filter_beroep_selected');
    $('#beroepsfilter').slideDown(400).addClass('filter_beroep_selected');
}

function closeFoldOutAppeals(buttonElm) {
//    $("#foldOutAppeal").slideUp(2000);
//    var btn = $('.lessAppeal');
//    btn.unbind();
//    btn.attr('class', 'moreAppeal');
//    btn.attr('href', '#scroll');
//    btn.text('Meer beroepen');
//    btn.click(function (e) { openFoldOutAppeals(); });
//    $('div.foldOut').localScroll({
//        easing: 'easeInQuad',
//        duration: 500
    //    });
    $(buttonElm).removeClass('filter_beroep_selected');
    $('#beroepsfilter').slideUp(400).removeClass('filter_beroep_selected');
}


function unselectFilter(selectedElement) {
    var listElement = $('#' + $(selectedElement).parent().attr('class') + ' a input[value="' + $(this).find('input').val() + '"]')
    $(selectedElement).parent().html('').hide();
    $("li.category, li.appeal").html('').hide();
    listElement.fadeIn();
    loadEducations();
}

function slider() {
    // Set up Sliders
	$('#slider1').anythingSlider({
		startStopped: true, // If autoPlay is on, this can force it to start stopped
		hashTags: false
	});
}

function mediaTargetedScript() {
    var mediaInspector = $('#mediaInspector');
    zIndex = $(mediaInspector).css('z-index');
    switch (parseInt(zIndex)) {
        case 1:
            // @media screen
            //$('.googleMap').show();
            //$('.staticMap').hide();
            break;
        case 2:
            // @media print
            //$('.googleMap').hide();
            //$('.staticMap').show();
            break;
    }
    //$('#mediaInspector').html($(mediaInspector).zIndex);
}

function openTwitter(url) {
    window.open(url, 'Deel dit op Twitter', 'status=1,toolbar=0,location=1,menubar=0,directories=0,resizable=1,scrollbars=0,height=400,width=533');
}

function openFacebook(url) {
    window.open(url, 'Deel dit op Facebook', 'status=1,toolbar=0,location=1,menubar=0,directories=0,resizable=1,scrollbars=0,height=400,width=533');
}

function openLinkedin(url) {
    window.open(url, 'Deel dit op LinkedIn', 'status=1,toolbar=0,location=1,menubar=0,directories=0,resizable=1,scrollbars=0,height=400,width=533');
}

function openHyves(url) {
    window.open(url, 'Deel dit op Hyves', 'status=1,toolbar=0,location=1,menubar=0,directories=0,resizable=1,scrollbars=0,height=450,width=533');
}

function loadEducations() {
    $('.imgLoader').removeClass('hidden');
    var form = null;
    var level = null;
    var cat = null;
    var appeals = null;

    var formFilter = $('#formTabs li.selected input[type=hidden]')[0];
    if (formFilter != null) { form = $(formFilter).val(); }

    var levelFilter = $('select#f_type')[0];
    if (levelFilter != null) { level = $(levelFilter).val(); }

    var catFilter = $('select#f_richting')[0];
    if (catFilter != null) { cat = $(catFilter).val(); }

    var appFilter = $('ul#filter li.appeal input[type=hidden]');
    if (appFilter.length != 0) {
        appeals = "";
        $(appFilter).each(function (i, item) {
            if (appeals != '') { appeals += ','; }
            appeals += $(item).val();
        });
    }

    var url = '?filter=1';
    if (form != null) { url += '&form=' + form; }
    if (level != null) { url += '&level=' + level; }
    if (cat != null) { url += '&cat=' + cat; }
    if (appeals != null) { url += '&appeals=' + appeals; }

    $.get(url, function (data) {
        renderEducations(data);
    });
}

function renderEducations(data) {
    $('#innerFormTabs').html($(data).find('#innerFormTabs').html());
    $('#trainingOverview').html($(data).find('#trainingOverview').html());

    $('.educations #formTabs li a').click(function (e) {
        $('#formTabs li').removeClass('selected');
        $(this).parent().addClass('selected');
        loadEducations();
    });
    $("#formsTrigger").hover(function () {

        var cleft = $(this).position().left + 50;


        $("#forms").css({'left':cleft}).fadeIn(200);
    }, function () {
        setTimeout('hideFormsTooltip()', 500);
    });

    $("#forms").hover(function () {
        mouseInFormsTooltip = true;
    }, function () {
        mouseInFormsTooltip = false;
        $("#forms").fadeOut(100);
    });

    $('.imgLoader').addClass('hidden');

    $(".educations #trainingOverview .training ul li").click(function () {
        if ($(this).find("a:first").is('*')) var link = $(this).find("a:first").attr('href');
        window.location = link;
        return false;
    });
}

function checkAppealsFoldoutHeaders() {
    $('.foldOutAppealColumn h4').each(function (i, item) {
        $(item).parent().prevAll('.foldOutAppealColumn').find('h4').each(function (i2, item2) {
            if ($(item2).text() == $(item).text()) { $(item).text($(item2).text() + ' (vervolgd)'); }
        });
    });
}

function filterAppeals() {
    var programs = $('.programItem');
    var appFilter = $('ul#filter li.appeal input[type=hidden]');
    if (appFilter.length != 0) {
        $(programs).each(function (i, item) {
            var found = false;
            var appeals = $(item).find('input.appeal').val();
            if (appeals != "") {
                $(appFilter).each(function (i2, item2) {
                    appeal = $(item2).val() || "";
                    if (!found && appeals.indexOf(appeal) != -1) {
                        found = true;
                    }
                });
            }
            if (!found) {
                $(item).hide();
            } else {
                $(item).show();
            }
        });
    }
    var clusters = $('.programCluster');
    $(clusters).each(function (i, item) {
        if ($(this).find('li:visible').length == 0) {
            $(this).hide();
        } else {
            $(this).show();
        }
    });
}

//function replaceTotalResults() {
//    var count = $('input#filterResultsCount').val();
//    var text = count;
//    if (count == 1) {
//        text += ' opleiding gevonden';
//    } else {
//        text += ' opleidingen gevonden';
//    }
//    $('.filter .titleLoader').html(text);
//}

// display tooltips op de filterpagina
var mouseInFormsTooltip;
var mouseInLevelsTooltip;
function displayTooltips() {
    $("#formsTrigger").hover(function () {
        $("#forms").fadeIn(200);
    }, function () {
        setTimeout('hideFormsTooltip()', 500);
    });
    $("#forms").hover(function () {
        mouseInFormsTooltip = true;
    }, function () {
        mouseInFormsTooltip = false;
        $("#forms").fadeOut(100);
    });
    $("#levelsTrigger").hover(function () {
        $("#levels").fadeIn(100);
    }, function () {
        setTimeout('hideLevelsTooltip()', 500);
    });
    $("#levels").hover(function () {
        mouseInLevelsTooltip = true;
    }, function () {
        mouseInLevelsTooltip = false;
        $("#levels").fadeOut(100);
    });

}

function hideFormsTooltip() {
    if (!mouseInFormsTooltip) {
        $("#forms").fadeOut(100);
    }
}

function hideLevelsTooltip() {
    if (!mouseInLevelsTooltip) {
        $("#levels").fadeOut(100);
    }
}

function initFacebook() {
    initFacebookAdd();
    initFacebookRemove();
}

function initFacebookAdd() {
    $('#fbAdd').unbind();
    $('#fbAdd').click(function () {
        FB.login(function (response) {
            if (response.session) {
                $('.imgLoader').removeClass('hidden');
                $('#facebookBlockHolder').load('?add=1 #facebookBlock', function () { $('.imgLoader').addClass('hidden'); initFacebookRemove(); });

            } else {
                // user cancelled login
            }
        }, { perms: 'offline_access' });
        return false;
    });
}

function initFacebookRemove() {
    $('#fbRemove').unbind();
    $('#fbRemove').click(function () {
        FB.login(function (response) {
            if (response.session) {
                $('.imgLoader').removeClass('hidden');
                $('#facebookBlockHolder').load('?remove=1 #facebookBlock', function () { $('.imgLoader').addClass('hidden'); initFacebookRemove(); });
                initFacebook();
            } else {
                // user cancelled login
            }
        });
        return false;
    });

}

function switchView(tab) {
    var tabNr = tab.attr('class');
    var tabsHolder = tab.parent().parent();
    tabsHolder.find('li').removeClass('selected');
    tab.parent().addClass('selected');
    var panelsHolder = tab.parent().parent().parent().parent();
    panelsHolder.children().each(function (i, item) {
        if ($(item).attr('class').startsWith('tab')) {
            if ($(item).attr('class') == tabNr) {
                $(item).show();
            } else {
                $(item).hide();
            }
        }
    });
}

function initPanorama() {
    var fc = $('#flashcontent');
    if (fc != null) {
        var panorama = fc.find('input[type="hidden"]').val();
        if (panorama != '') {
            var flashvars = {};
            var params = {
                allowFullScreen: 'true',
                allowScriptAccess: 'sameDomain',
                flashvars: 'xml_file=/panoramas/' + panorama + '/files/navigation.xml'
            };
            var attributes = {};
            swfobject.embedSWF('/panoramas/' + panorama + '/files/pano.swf', 'flashcontent', '690px', '315px', '9.0.0', '#282828', flashvars, params, attributes);
        }
    }
}

/* function accordion */

function createAccordion(element) {

    if ($(element).is('*') == null) return false;

    $(element).each(function (i) {
        $(this).next().hide();
        $(this).next().addClass('accordion_content');
        var n = 1;

        $(this).hover(
          function () {
              $(this).addClass("accordion_hover");

          },
          function () {
              if ($(this).hasClass('active') != true) {
                  $(this).removeClass("accordion_hover");

              }
          }
        );

        $(this).click(function (e) {
            n *= -1;

            var el = $(this);
            var nel = $(this).next();
            $.each($('.accordion_content'), function () {
                if ($(this)[0] != nel[0]) {
                    $(this).prev().removeClass('active');
                    $(this).prev().removeClass('accordion_hover');
                    $(this).slideUp();
                } else {
                    if (el.hasClass('active')) {
                        $(this).fadeOut(300);
                        $(this).prev().removeClass('active');
                        $(this).prev().removeClass('accordion_hover');
                    } else {
                        $(this).fadeIn(500);
                        $(this).prev().addClass('active');
                        $(this).prev().addClass('accordion_hover');
                    }
                }
            })
            e.preventDefault();
        })
    })
}


function createAccItem(e) {
    //console.log('running: ' + e);
}
$(document).ready(function () {
    createAccordion('.accordion');
    checkSelectedEducation();

	$('ul.thumbNav>li img').hover(function(e){
		if (e.type == 'mouseenter') {
			$(this).stop(true,false).fadeTo('fast',0.8);
		} else {
			$(this).stop(true,false).fadeTo('fast',1);
		}
	});

});
