(function (a) {

    a.fn.extend({
        reflect: function (b) {

            b = a.extend({
                height: 1 / 3,
                opacity: 0.5
            }, b);
            return this.unreflect().each(function () {
                var c = this;
                if (/^img$/i.test(c.tagName)) {
                    function d() {
                        var g = c.width,
                            f = c.height,
                            l, i, m, h, k;
                        i = Math.floor((b.height > 1) ? Math.min(f, b.height) : f * b.height);
                        l = a("<canvas />")[0];
                        if (l.getContext) {
                            h = l.getContext("2d");
                            try {
                                a(l).attr({
                                    width: g,
                                    height: i
                                });
                                h.save();
                                h.translate(0, f - 1);
                                h.scale(1, -1);
                                h.drawImage(c, 0, 0, g, f);
                                h.restore();
                                h.globalCompositeOperation = "destination-out";
                                k = h.createLinearGradient(0, 0, 0, i);
                                k.addColorStop(0, "rgba(255, 255, 255, " + (1 - b.opacity) + ")");
                                k.addColorStop(1, "rgba(255, 255, 255, 1.0)");
                                h.fillStyle = k;
                                h.rect(0, 0, g, i);
                                h.fill()
                            } catch (j) {
                                return
                            }
                        } else {
                            if (!a.browser.msie) {
                                return
                            }
                            l = a("<img />").attr("src", c.src).css({
                                width: g,
                                height: f,
                                marginBottom: i - f,
                                filter: "FlipV progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (b.opacity * 100) + ", FinishOpacity=0, Style=1, StartX=0, StartY=0, FinishX=0, FinishY=" + (i / f * 100) + ")"
                            })[0]
                        }
                        a(l).css({
                            display: "block",
                            border: 0
                        });
                        m = a(/^a$/i.test(c.parentNode.tagName) ? "<span />" : "<div />").insertAfter(c).append([c, l])[0];
                        m.className = c.className;
                        a.data(c, "reflected", m.style.cssText = c.style.cssText);
                        a(m).css({
                            width: g,
                            height: f + i,
                            overflow: "hidden"
                        });
                        c.style.cssText = "display: block; border: 0px";
                        c.className = "reflected"
                    }
                    if (c.complete) {
                        d()
                    } else {
                        a(c).load(d)
                    }
                }
            })
        },
        unreflect: function () {
            return this.unbind("load").each(function () {
                var c = this,
                    b = a.data(this, "reflected"),
                    d;
                if (b !== undefined) {
                    d = c.parentNode;
                    c.className = d.className;
                    c.style.cssText = b;
                    a.removeData(c, "reflected");
                    d.parentNode.replaceChild(c, d)
                }
            })
        }
    })

})(jQuery);


$.fn.shuffle = function() {
        return this.each(function(){
            var items = $(this).children().clone(true);
            return (items.length) ? $(this).html($.shuffle(items)) : this;
        });
    }
    
    $.shuffle = function(arr) {
        for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
        return arr;
    }

$.fn.autoHeightColumn = function(){
	var columnOneHeight = $('.cl-column.column-one').height();
	var columnTwoHeight = $('.cl-column.column-two').height();

	if (columnOneHeight > columnTwoHeight){
		var columnOneHeight = columnOneHeight + 'px';		
		$('.cl-column.column-one').css('height', columnOneHeight);
		$('.cl-column.column-two').css('height', columnOneHeight);
	};
	if (columnOneHeight < columnTwoHeight){
		var columnTwoHeight = columnTwoHeight + 'px';
		$('.cl-column.column-one').css('height', columnTwoHeight);
		$('.cl-column.column-two').css('height', columnTwoHeight);
	};
}
$.fn.autoHeightRC = function(){
	var columnOneHeight = $('#main-content.related').height();
	var columnTwoHeight = $('#related-content').height();

	if (columnOneHeight > columnTwoHeight){
		var columnHeight = columnOneHeight + 'px';		
	};
	if (columnOneHeight < columnTwoHeight){
		var columnHeight = columnTwoHeight + 'px';
	};
	
	$('.related').css('height', columnHeight);
	$('#related-content').css('height', columnHeight);
	
	
};
	
$.fn.pickThree = function (list) {	
	randomElements = jQuery(this).get().sort(function(){ 
		return Math.round(Math.random())-0.5}).slice(0,3)

		var $allLi = $(this), // All
			showRandom = function() {
				$allLi.hide().sort(function() { // Hide all, then sort
					return Math.round(Math.random()) - 0.5;
				}).slice(0, 3).show().addClass("showed"); // Show first five after randomizing
			};	

	showRandom(); 
};	

$.fn.headerfader = function() {

	var randomactive = $('#header .wpg-header li')[Math.random()*$('#header .wpg-header li').length|0];
	$(randomactive).addClass('active');
	
	var nextImage = function() {
		var $active = $('#header .wpg-header li.active');
		
		var $next = $active.next();    

		$active.addClass('last-active');

		$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 2000, function() {
            $active.removeClass('active last-active');
        });
		if ( $next.length == 0) {
			$('#header .wpg-header li:first').css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 2000, function() {
            $active.removeClass('active last-active');
        });};

	};
	setInterval(nextImage, 5000)
};



$.fn.footerimages = function() {  
  $.each(this, function(){
   
   var imageWidth = $(this).width() / 2;
   var imageHeight = $(this).height() / 2;
   var imageMarginMin = "-"+imageHeight+"px";
   var imageMarginWidthMin = "-"+imageWidth+"px";
   
   var cssArray = new Array;
   cssArray = [{'position':'absolute','marginTop':imageMarginMin,'marginLeft':imageMarginWidthMin,'margin-top':imageMarginMin,'margin-left':imageMarginWidthMin,'top':'50%','left':'50%'}];
   $(this).css(cssArray[0]);
  });
};

$.fn.launchnav = function() {
	var level1 = $('#navigation ul.nav1');
	var level2 = $('#navigation ul.nav2');
	
	if(level1.length > 0){
		
		level1.parent().append("<div class=open></div>");
		level1.append("<div class=kiespijler>Kies een van onze pijlers</div>").append("<div class=close></div>");		
		level1.siblings('a').attr("href", "#").click(function() {
			level1.slideToggle("fast").parent().toggleClass("active");;	
			$('#navigation ul li.current').toggleClass("none");
		});
		$('#navigation ul.nav1 div.close').click(function() {
			level1.slideToggle("fast").parent().toggleClass("active");
			$('#navigation ul li.current').toggleClass("none");
		});
	}
	if(level2.length > 0){
		
		level2.siblings('a').attr("href", "#");	
		$('#navigation li#nav-item-4-1 ul.nav2 ').siblings('a').click(function() {
			level2.addClass("hidden");	
			$(this).siblings('ul').removeClass("hidden").addClass("visible");
			$('#navigation .kiespijler').addClass("hidden");
			$(this).parent().siblings('li').removeClass('active');
			$(this).parent('li#nav-item-4-1').addClass('active');
		});
		$('#navigation li#nav-item-4-2 ul.nav2 ').siblings('a').click(function() {
			level2.addClass("hidden");	
			$(this).siblings('ul').removeClass("hidden").addClass("visible");
			$('#navigation .kiespijler').addClass("hidden");
			$(this).parent().siblings('li').removeClass('active');
			$(this).parent('li#nav-item-4-2').addClass('active');
		});
		$('#navigation li#nav-item-4-3 ul.nav2 ').siblings('a').click(function() {
			level2.addClass("hidden");	
			$(this).siblings('ul').removeClass("hidden").addClass("visible");
			$('#navigation .kiespijler').addClass("hidden");
			$(this).parent().siblings('li').removeClass('active');
			$(this).parent('li#nav-item-4-3').addClass('active');
		});
		$('#navigation li#nav-item-4-4 ul.nav2 ').siblings('a').click(function() {
			level2.addClass("hidden");	
			$(this).siblings('ul').removeClass("hidden").addClass("visible");
			$('#navigation .kiespijler').addClass("hidden");
			$(this).parent().siblings('li').removeClass('active');
			$(this).parent('li#nav-item-4-4').addClass('active');
		});	
	}
	level1.mouseleave(function(){
		setTimeout(function(){
		level1.slideUp("slow").parent().removeClass("active");
		$('#navigation ul li.current').removeClass("none");		
		}, 2000);
	});


};

    jQuery.fn.extend({
			/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la)
			 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
			 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
			 *
			 * Version: 0.2.5
			 * 
			 */
	
        slimScroll: function(o) {
            var ops = o;
            //do it for every element that matches selector
            this.each(function(){
            var isOverPanel, isOverBar, isDragg, queueHide, barHeight,
                divS = '<div></div>',
                minBarHeight = 30,
                wheelStep = 30,
                o = ops || {},
                cwidth = o.width || 'auto',
                cheight = o.height || '250px',
                size = o.size || '7px',
                color = o.color || '#000',
                position = o.position || 'right',
                opacity = o.opacity || .4,
                alwaysVisible = o.alwaysVisible === true;
            
                //used in event handlers and for better minification
                var me = $(this);

                //wrap content
                var wrapper = $(divS).css({
                    position: 'relative',
                    overflow: 'hidden',
                    width: cwidth,
                    height: cheight
                }).attr({ 'class': 'slimScrollDiv' });

                //update style for the div
                me.css({
                    overflow: 'hidden',
                    width: cwidth,
                    height: cheight
                });

                //create scrollbar rail
                var rail  = $(divS).css({
                    width: '15px',
                    height: '100%',
                    position: 'absolute',
                    top: 0
                });

                //create scrollbar
                var bar = $(divS).attr({ 
                    'class': 'slimScrollBar '
                    }).css({
                        background: color,
                        width: size,
                        position: 'absolute',
                        top: 0,
                        opacity: opacity,
                        display: alwaysVisible ? 'block' : 'none',
                        zIndex: 99
                });

                //set position
                var posCss = (position == 'right') ? { right: '1px' } : { left: '1px' };
                rail.css(posCss);
                bar.css(posCss);

                //wrap it
                me.wrap(wrapper);

                //append to parent div
                me.parent().append(bar);
                me.parent().append(rail);

                //make it draggable
                bar.draggable({ 
                    axis: 'y', 
                    containment: 'parent',
                    start: function() { isDragg = true; },
                    stop: function() { isDragg = false; hideBar(); },
                    drag: function(e) 
                    { 
                        //scroll content
                        scrollContent(0, $(this).position().top, false);
                    }
                });

                //on rail over
                rail.hover(function(){
                    showBar();
                }, function(){
                    hideBar();
                });

                //on bar over
                bar.hover(function(){
                    isOverBar = true;
                }, function(){
                    isOverBar = false;
                });

                //show on parent mouseover
                me.hover(function(){
                    isOverPanel = true;
                    showBar();
                    hideBar();
                }, function(){
                    isOverPanel = false;
                    hideBar();
                });

                var _onWheel = function(e)
                {
                    //use mouse wheel only when mouse is over
                    if (!isOverPanel) { return; }

                    var e = e || window.event;

                    var delta = 0;
                    if (e.wheelDelta) { delta = -e.wheelDelta/120; }
                    if (e.detail) { delta = e.detail / 3; }

                    //scroll content
                    scrollContent(0, delta, true);

                    //stop window scroll
                    if (e.preventDefault) { e.preventDefault(); }
                    e.returnValue = false;
                }

                var scrollContent = function(x, y, isWheel)
                {
                    var delta = y;

                    if (isWheel)
                    {
                        //move bar with mouse wheel
                        delta = bar.position().top + y * wheelStep;

                        //move bar, make sure it doesn't go out
                        delta = Math.max(delta, 0);
                        var maxTop = me.outerHeight() - bar.outerHeight();
                        delta = Math.min(delta, maxTop);

                        //scroll the scrollbar
                        bar.css({ top: delta + 'px' });
                    }

                    //calculate actual scroll amount
                    percentScroll = parseInt(bar.position().top) / (me.outerHeight() - bar.outerHeight());
                    delta = percentScroll * (me[0].scrollHeight - me.outerHeight());

                    //scroll content
                    me.scrollTop(delta);

                    //ensure bar is visible
                    showBar();
                }

                var attachWheel = function()
                {
                    if (window.addEventListener)
                    {
                        this.addEventListener('DOMMouseScroll', _onWheel, false );
                        this.addEventListener('mousewheel', _onWheel, false );
                    } 
                    else
                    {
                        document.attachEvent("onmousewheel", _onWheel)
                    }
                }

                //attach scroll events
                attachWheel();

                var getBarHeight = function()
                {
                    //calculate scrollbar height and make sure it is not too small
                    barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight);
                    bar.css({ height: barHeight + 'px' });
                }

                //set up initial height
                getBarHeight();

                var showBar = function()
                {
                    //recalculate bar height
                    getBarHeight();
                    clearTimeout(queueHide);
                    
                    //show only when required
                    if(barHeight >= me.outerHeight()) {
                        return;
                    }
                    bar.fadeIn('fast');
                }

                var hideBar = function()
                {
                    //only hide when options allow it
                    if (!alwaysVisible)
                    {
                        queueHide = setTimeout(function(){
                            if (!isOverBar && !isDragg) { bar.fadeOut('slow'); }
                        }, 1000);
                    }
                }

            });
            
            //maintain chainability
            return this;
        }
    });

    jQuery.fn.extend({
        slimscroll: jQuery.fn.slimScroll
    });

$.fn.searchExtraDivs = function(){ 
	this.find('.searchresults:contains("[1-10]")').wrap("<span />");
	$('.searchresults > p').wrapAll('<div class="resultcount" />');
};
	
$(document).ready(function() {	
	
	/* header slider with fading in&out */
	$(".elements-collection-list.wpg-header li").headerfader();
	
	/* adds a unique number class to the media overview elements */
	$(".homepage .column-one .media-overview").each(function (i, element) {
		i = i+1;		
		$(this).addClass("number" + i);		
		
	})
	$(".media-overview.pijler").each(function (i, element) {
		i = i+1;		
		$(this).addClass("number" + i);		
	})		
	
	/* randomizer */
	$(".media-overview.pijler.number1 li").pickThree();
	$(".media-overview.pijler.number2 li").pickThree();
	$(".media-overview.pijler.number3 li").pickThree();

	/* adds unique class for styling purposes */	
	$(".media-overview.pijler .showed").each(function (i, element) {
		i = i+1;
		$(this).addClass("image" + i);
	})
	
	/* adds Class related when there is an related content */
	if($('#related-content').length > 0){
		$('#main-content').addClass('related');
	}
	/* adds Class no-column when there is no column */
	if($('.cl-column').length == 0){
		$('#main-content').addClass('no-column');
	}
	
	/* calculates the height of largest column and append it to the smallest column */
	$("#five-column-layout .cl-column.column-one, #five-column-layout .cl-column.column-one").autoHeightColumn();
	$('.related').autoHeightRC();
	
	/* image reflection */
	$(".homepage .media-overview .showed").find('img').reflect();
	
	/* navigation */
	$('#navigation').launchnav();

	/* append hyperlink to publischers pages */
	$('.media-overview.pijler:contains("Educatief")').addClass('educatief').append('<a href="/uitgeverijen/educatief.htm" class="readmore">Alle methoden</a>').click(function(){
		 window.location=$(this).find("a.readmore").attr("href"); return false;}	);
	$('.media-overview.pijler:contains("Boeken")').addClass('boeken').append('<a href="/uitgeverijen/boeken.htm" class="readmore">Alle uitgeverijen</a>').click(function(){
		 window.location=$(this).find("a.readmore").attr("href"); return false;}	);
	$('.media-overview.pijler:contains("Tijdschriften")').addClass('tijdschriften').append('<a href="/uitgeverijen/tijdschriften.htm" class="readmore">Alle titels</a>').click(function(){
		 window.location=$(this).find("a.readmore").attr("href"); return false;}	);	
		 
	/* puts reaction form to bottom of page */
	$('#main-content').find('form#f175280f').appendTo('#main-content');

	/* copy breadcrumbs to bottom of page */
	if ( $("#breadcrumbs").find('em').length > 0 ) {

		if ( $(".column-one").length > 0 ) {
			$("#breadcrumbs").clone().appendTo(".column-one").addClass('bottom');
		}
		else{
			$("#breadcrumbs").clone().appendTo("#main-content").addClass('bottom');
		}

	}
	
	/*changes button "lees meer" to "alle vacatures" */
	$(".homepage .column-two .link").find("span").html('Alle vacatures');
	
	/* adds scroll on hover */
	$(".homepage .column-three .media-overview").slimScroll({
                  color: '#000',
                  size: '10px',
                  width: '279px',
                  height: '350px'                  
              });
			  	
	/* shuffles the list items in the footer */
    $('#footer .elements-collection-list').find('ul').shuffle();
	
	/* calculates the right margin for positioning footer images */
	$("#footer").find('img').footerimages();
	
	/* ie 6-7 hack for focus on inputfields*/
	if (jQuery.browser.msie === true) {
        jQuery('input')
                .bind('focus', function() {
                        $(this).addClass('ieFocus');
                }).bind('blur', function() {
                        $(this).removeClass('ieFocus');
                });
    }
	$(".searchresults").searchExtraDivs();
});
