
/* Initialize */
jQuery(
  
  function ($) {
	  
	$('html').removeClass('no-js');
	if ($.browser.opera) $('html').addClass('no-pointerevents');
	  
	$.Body = $('body');
    
    $.Window = $(window);
    
    $.Scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $.Body;
	
	$('[data-controller]').Instantiate();
	
	// Bug with IE canvas implementation requires onload
    if ($.browser.msie)
      $(window).bind('load',function(){$('section canvas').Background();})
    else
      $('section canvas').Background();
	  	  
	 $(window).bind('resize',function(){$('section canvas').Background();})
	 
	 $.Window.scroll();
  }
);

/* ---------------------------------- */

/* Events */

(function($) {

  $.Events = {
     
     SECTION_ENTER: 'sectionEnter',
     SCROLL_TO: 'scrollTo',
     SCROLL: 'windowScroll',
     SCROLL_ENTER: 'windowScrollEnter',
     SCROLL_LEAVE: 'windwScrollLeave',
     
     KEY_UP: 'keyUp',
     KEY_DOWN: 'keyDown',
     KEY_LEFT: 'keyLeft',
     KEY_RIGHT: 'keyRight',
     KEY_ESC: 'keyEsc',
     KEY_SPACE: 'keySpace'
    
  
  } // Events  
  
  $.Views = {
  
  
  } // Views 

   
  
})(jQuery);

/* ---------------------------------- */

/* Instantiate */

(function($) {

  $.fn.Instantiate = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 

          var $self = $(this),
              $controller = $self.attr('data-controller');
                  
          if ($self[$controller]) $self[$controller]();
              
      });
      
  }
    
  

})(jQuery);

/* ---------------------------------- */

/* Background */

(function($) {

  $.fn.Background = function(settings) {
	  
	  var config = {};
 
      if (settings) $.extend(config, settings);
		
      this.each(function() { 
	  
        var $self = $(this),
            $canvas_id = $self.attr('id'),
            $color = $self.attr('data-bgcolor') ? $self.attr('data-bgcolor') : '#ffffff',
			$top = $self.attr('data-top') ? Number($self.attr('data-top')) : 0,
            _canvas = document.getElementById($canvas_id);
			if ($.browser.msie && (typeof(G_vmlCanvasManager) != 'undefined')) { // ie IE
                _canvas = G_vmlCanvasManager.initElement(_canvas);
       		 }

         var _canvas_ctx = _canvas.getContext('2d'),
			_height = 1034,
			_width = ($(window).width()<960)? 960 : $(window).width(),
			_shape = [	[_width, 0], [_width, _height], [0, (_width+_height)], [0, _width] ];
							
			$self.attr({height: _width+_height ,width: _width});
			$self.css({top: (_width<960) ? $top-480 : parseInt(-_width/2)});
			
        	_canvas_ctx.fillStyle = $color;
			_canvas_ctx.beginPath();
			_canvas_ctx.moveTo(_shape[0][0],_shape[0][1]);
            for(p in _shape)if (p > 0)_canvas_ctx.lineTo(_shape[p][0],_shape[p][1]);

            _canvas_ctx.lineTo(_shape[0][0],_shape[0][1]);
            _canvas_ctx.fill();
      });
      
      return this;
  }

})(jQuery); 

/* ---------------------------------- */

/* NavBackground */

(function($) {

  $.fn.NavBackground = function(settings) {
	  
	  var config = {};
 
      if (settings) $.extend(config, settings);
		
      this.each(function() { 
	  
        var $self = $(this);
           
			    
      });
      
      return this;
  }

})(jQuery); 

/* ---------------------------------- */

/* NavBackground */

(function($) {

  $.fn.MainNav = function() {
	  
	  this.each(function(){
		  
		  var $self = $(this),
          $listItems = $('li', this);
		  
		  $listItems.each(function(i){
				var li = $(this),
				$id = li.attr('data-nav');
				li.bind('click',function(e){ 
                  $.Body.triggerHandler($.Events.SCROLL_TO,$id);
                  e.preventDefault();
                })
				$.Body.bind($.Events.SECTION_ENTER,function(e,id){
				  if (id==$id)
					li.addClass('active');
				  else
					li.removeClass('active');
           		 });
          })
	  });
	  
  return this;
  
  }
  
})(jQuery);

/* ---------------------------------- */

/* SiteScroll */

(function($) {
  
   $.fn.SiteScroll = function() {
   
     this.each(function() { 
    
        $.Body.bind($.Events.SCROLL_TO,function(e,id){$.Scroll.stop().animate({ 'scrollTop': $('#'+id).offset().top },800,'easeInOutQuart');})
           
     });
     
    return this;
     
  }
 
})(jQuery);

/* ---------------------------------- */

/* Scrollable */

(function($) {
	
  $.fn.Scrollable = function(settings) {
   
     var config = { threshold: 0, offset_scroll: 6, offset_intertia: .15 };
 
     if (settings) $.extend(config, settings);
    
     this.each(function() { 
      
        var $self = $(this),
        $id = $self.attr('id');
        
        $.Window.bind('scroll',function(e){
            
              if ( $.inview($self,{threshold:config.threshold}) ) {
                
                if (!$self.hasClass('active')){
                
                  $self.addClass('active');                
                  if (config.is_nav)
                    $.Body.triggerHandler($.Events.SECTION_ENTER,$id);
					$self.triggerHandler($.Events.SCROLL_ENTER);
                }
                  
                $self.triggerHandler($.Events.SCROLL,$.distancefromfold($self,{threshold:config.threshold}) - config.threshold)
                
              }else{
                
                if ($self.hasClass('active'))
					$self.removeClass('active');
                  	$self.triggerHandler($.Events.SCROLL_LEAVE);
              }
            
            });               
            
     });
     
    return this;
     
  } 
  
})(jQuery);
  
/* ---------------------------------- */

/* Sections */

(function($) {
  
  $.fn.Home = function() {
   
     this.each(function() { 
      
        var $self = $(this),
			$images = $self.find('figure img'),
			$current = $images.first();
			_interval = 0,
			_index = 0;
        
        $self.Scrollable({threshold: 0,is_nav:true})
			 .bind($.Events.SCROLL_ENTER,on_scroll_enter)
             .bind($.Events.SCROLL_LEAVE,on_scroll_leave);	 
				
		if($images.length>1){
		
			var $pager = $self.find('.pager'),
			$ul = $('<ul/>').appendTo($pager),
			_links = new Array();
		
			$images.each(function(i){
				var $image = $(this).css({opacity:0}),
				$li = $('<li><a href="#">'+i+'</a></li>')
				.bind('click', function(e){kill_timer(); showImage(e, this, $image)})
				.bind('show', function(e){showImage(e, this, $image)})
				.appendTo($ul);
				_links.push($li);
				if(i==0) {
					$image.css({opacity:1, left:-900}).animate({left: -1000}, 1000, 'easeOutSine'); 
					$li.addClass('active');
				}
			  });
		}
		  
		function showImage(e, el, $image){
			
			var index = $(el).index();
			$(el).addClass('active').siblings().removeClass('active');
			$current.stop().animate({left: -1200, opacity:0}, 1000, 'easeInOutSine');
			$current = $images.eq(index).css({left:-900}).stop().animate({left: -1000, opacity:1}, 1000, 'easeOutSine');
			e.preventDefault();
		}
		  
		function next(){
			var index = ($current.index() === ($images.length-1)) ? 0 : $current.index()+1;
			_links[index].trigger('show');
		}
		  
		function set_timer() {
            _interval = setInterval(next, 4000);
        }
        
        function kill_timer() {
            clearInterval(_interval);
        }
		
		function on_scroll_enter(e) {
			set_timer();
        }
        
        function on_scroll_leave(e) {
        	kill_timer();
        }
            
     });
     
    return this;
     
  } //Home
  
   $.fn.Verhaal = function() {
   
     this.each(function() { 
      
        var $self = $(this),
			$articles = $('#verhaal section article'),
			$images = $('#verhaal figure img'),
			$next = $('nav.prevnext .next').bind('click', next),
			$prev = $('nav.prevnext .prev').bind('click', prev),
			_index = 0;
			
			$images.bind('onload', function(e){
					if ($.browser.msie){
						 (e.target != $images[_index])? $(e.target).css({display: 'none'}) : $(e.target).css({display: 'block'});
						 return;
					}
					(e.target != $images[_index])? $(e.target).css({opacity:0}) : $(e.target).css({opacity: 0}).animate({opacity:1}, 800, 'easeOutSine');});
			$images.lazyload({event:'onshow'});
        
        $self.Scrollable({threshold: -200,is_nav:true})
			 .bind($.Events.SCROLL_ENTER,on_scroll_enter)
             .bind($.Events.SCROLL_LEAVE,on_scroll_leave);
		
		if($articles.length>1){
		
			var $pager = $self.find('.pager'),
			$ul = $('<ul/>').appendTo($pager),
			_links = new Array();
		
			$articles.each(function(i){
				var $article = $(this).css({opacity:0, left:150}),
					$image = $images.eq(i);
					$li = $('<li><a href="#">'+i+'</a></li>')
					.bind('click', function(e){showArticle(e, this, $article, $image)})
					.bind('show', function(e){showArticle(e, this, $article, $image)})
					.appendTo($ul);
					_links.push($li);
				if(i==0) {
					$article.css({opacity:1, left:70});
					$li.addClass('active');
				}
			  });
		}
		  
		function showArticle(e, el, $image){
			
			_index = $(el).index();
			$(el).addClass('active').siblings().removeClass('active');
			$articles.eq(_index).stop().animate({opacity:1, left:70}, 800, 'easeOutSine').siblings().css({opacity:0, left:150});
			if ($.browser.msie){
				$images.eq(_index).css({display: 'block'}).siblings().css({display: 'none'});
			} else {
				$images.eq(_index).stop().animate({opacity:1}, 800, 'easeOutSine').siblings().css({opacity:0});
			}
			e.preventDefault();
		}
		  
		function next(e){
			var index = (_index == ($images.length-1)) ? 0 : _index+1;
			_links[index].trigger('show');
			e.preventDefault();
		}
		
		function prev(e){
			var index = (_index == 0) ? $images.length-1 : _index-1;
			_links[index].trigger('show');
			e.preventDefault();
		}
		
		function on_scroll_enter(e) {
        	 $images.trigger('onshow');
        }
        
        function on_scroll_leave(e) {
        	
        }
            
     });
     
    return this;
     
  } //Verhaal
  
  $.fn.Kaart = function() {
   
     this.each(function() { 
      
        var $self = $(this),
			$pager = $self.find('#kaart-pager'),
			$images = $self.find('figure.bg img'),
			_menu = "nav-kaart-gerechten",
			_index = 0;
			
			$images.bind('onload', function(e){
				if ($.browser.msie){
					(e.target != $images[_index])? $(e.target).css({display:'none'}) : $(e.target).css({display:'block'});
				}else{
					(e.target != $images[_index])? $(e.target).css({opacity: 0}) : $(e.target).css({opacity: 0}).animate({opacity:1}, 800, 'easeOutSine');
				}
			});
			$images.lazyload({event:'onshow'});
			
			$self.find('#nav-kaart-gerechten li').each(addMenuEvent).first().trigger('click');
			$self.find('#nav-kaart-wijnen li').each(addMenuEvent);
			$self.Scrollable({threshold: -200,is_nav:true}).bind($.Events.SCROLL_ENTER,on_scroll_enter);
		
		function addMenuEvent(){
			var $self = $(this),
				$section = $('#'+$self.attr('data-nav'));
				
			$self.bind('click', function(e){
				var id =  $self.parent().parent().attr('id');
				$('#nav-kaart-gerechten li').removeClass('active');
				$('#nav-kaart-wijnen li').removeClass('active');
				$('#kaart section').removeClass('active').hide();
				$self.addClass('active');
				$section.show().addClass('active');
				buildPager($section);				
				if(_menu != id) {
					_menu = id; _index = (_index == 0)? 1 : 0;
					$images.hide();
					if ($.browser.msie){
						$images.eq(_index).css({display:'block'});
					} else {
						$images.eq(_index).css({display:'block', opacity:0}).animate({opacity:1}, 800, 'easeOutSine');
					}
				}
				e.preventDefault();
			});
		}
		
		function buildPager($section){
			
			$pager.html('');
			
			var $ul = $('<ul/>').appendTo($pager),
				$article = $section.find('article').first(),
				$menulist = $article.find('dl').first().css({top:0}),
				h = $article.height(),
				n = Math.ceil($menulist.height()/h);
				
			if(n<=1) return;
				
			for(var i=0; i<n; i++){
				var $li = $('<li><a href="#">'+i+'</a></li>').bind('click', function(e){showPage(e, this, $menulist, h)}).appendTo($ul);
				if(i==0) $li.addClass('active');
			}
		}
		
		function showPage(e, el, $menulist, h){
			var index = $(el).index();
			$(el).addClass('active').siblings().removeClass('active');
			$menulist.stop().animate({top:-h*index}, 300, 'easeInOutSine');
			e.preventDefault();
		}
		
		function on_scroll_enter(e) {
        	$images.trigger('onshow');
        }
            
     });
     
    return this;
     
  } //Kaart
  
  
  $.fn.Galerij = function() {
   
     this.each(function() { 
      
        var $self = $(this),
			$pager = $self.find('#galerij-pager');
			
			$self.find('#nav-galerij-video li').each(addMenuEvent);
			$self.find('#nav-galerij-foto li').each(addMenuEvent).first().trigger('click');
			
		
		function addMenuEvent(){
			var $self = $(this),
				$section = $('#'+$self.attr('data-nav')),
				$images = $section.find('img');
				
			$section.find('a').fancybox({padding:3});	
			
			$self.bind('click', function(e){
				
				var loader = ($(this).parent().parent().attr('id') == 'nav-galerij-foto') ? 'images/galerij_pict_loader.gif' : 'images/galerij_video_loader.gif' ;
				
				$('#nav-galerij-foto li').removeClass('active');
				$('#nav-galerij-video li').removeClass('active');
				$('#galerij section').removeClass('active').hide();
				$self.addClass('active');
				$section.show().addClass('active');
				
				$images.bind('onload', function(e){$(e.target).show()});
				$images.lazyload({event:'onshow', placeholder:loader});
				
				buildPager($section);
				
				$images.trigger('onshow');
				
				e.preventDefault();
			});
		}
		
		function buildPager($section){
			
			$pager.html('');
			
			var $ul = $('<ul/>').appendTo($pager),
				$contactsheet = $section.find('div.contact-sheet').first(),
				$figure = $contactsheet.find('figure').first().css({display:'block', top:0}),
				h = $contactsheet.height(),
				n = Math.ceil($figure.height()/h);
				
				if(n<=1) return;
				
			for(var i=0; i<n; i++){
				var $li = $('<li><a href="#">'+i+'</a></li>').bind('click', function(e){showPage(e, this, $figure, h)}).appendTo($ul);
				if(i==0) $li.addClass('active');
			}
		}
		
		function showPage(e, el, $figure, h){
			$(el).addClass('active').siblings().removeClass('active');
			var index = $(el).index();
			$figure.stop().animate({top:-h*index}, 0, 'easeOutSine');
			e.preventDefault();
		}
        
        $self.Scrollable({threshold: -200,is_nav:true})
            
     });
     
    return this;
     
  } //Galerij
  
  $.fn.Nieuwsandpers = function() {
   
     this.each(function() { 
      
        var $self = $(this),
		$images = $('#pers img');
        $self.Scrollable({threshold: -200,is_nav:true}).bind($.Events.SCROLL_ENTER,on_scroll_enter);
		
		function on_scroll_enter(e) {
        	$images.trigger('onshow');
        }
            
     });
     
    return this;
     
  } //Nieuwsandpers
  
  $.fn.Nieuws = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $pager = $self.find('#nieuws-pager');
		
		buildPager($self);
		
		function buildPager($section){
			
			$pager.html('');
			
			var $ul = $('<ul/>').appendTo($pager),
				$container = $section,
				$articles = $section.find('article');
				
				if($articles.length<1) return;
				
			
			$articles.each(function(i, article){
				var $article = $(article);
				var title = $article.find('h3').html();
				$article.find('a.leuk-bt').bind('click',function(e){
				  var w = window.open('http://www.facebook.com/sharer.php?s=100&p[url]=http://www.labotte.be&p[title]='+escape(title)+'&p[images][0]=http://www.labotte.be/images/labotte_logo_small.gif' ,'_fb','width=550,height=450')
				  w.focus();
				  e.preventDefault();
            	});

				var $li = $('<li><a href="#">'+i+'</a></li>').bind('click', function(e){showPage(e, this, $article)}).appendTo($ul);
				if(i==0) $li.addClass('active');
			});
		}
		
		function showPage(e, el, $article){
			$(el).addClass('active').siblings().removeClass('active');
			var index = $(el).index();
			$article.stop().css({left:370}).addClass('active').animate({left:0}, 250, 'easeOutSine').siblings('article').removeClass('active');
			e.preventDefault();
		}
        
            
     });
     
    return this;
     
  } //Nieuws
  
  $.fn.Pers = function() {
   
     this.each(function() { 
      
        var $self = $(this),
			$pager = $self.find('#pers-pager'),
			$images = $self.find('figure img');
		
		//$self.find('figure a').fancybox({padding:3});	
		//$images.bind('onload', function(e){$(e.target).show()});
		//$images.lazyload({event:'onshow'});
			
		buildPager($self);
		
		function buildPager($section){
			
			$('#pers-pager').html('');
			
			var $ul = $('<ul/>').appendTo('#pers-pager'),
				$contactsheet = $section.find('div.contact-sheet').first(),
				$figure = $contactsheet.find('figure').first().css({top:0}),
				h = $contactsheet.height(),
				n = Math.ceil($figure.height()/h);
				
				if(n<=1) return;
				
			for(var i=0; i<n; i++){
				var $li = $('<li><a href="#">'+i+'</a></li>').bind('click', function(e){showPage(e, this, $figure, h)}).appendTo($ul);
				if(i==0) $li.addClass('active');
			}
		}
		
		function showPage(e, el, $figure, h){
			$(el).addClass('active').siblings().removeClass('active');
			var index = $(el).index();
			$figure.stop().animate({top:-h*index}, 200, 'easeOutSine');
			e.preventDefault();
		}
        
            
     });
     
    return this;
     
  } //Pers
  
  $.fn.Vacatures = function() {
   
     this.each(function() { 
      
        var $self = $(this);
        $self.Scrollable({threshold: -200,is_nav:true})
            
     });
     
    return this;
     
  } //Vacatures  
  
})(jQuery);


/* ---------------------------------- */

/* Lazyload */
(function($){
	$.fn.lazyload=function(options){
		var settings = {threshold:0,failurelimit:0,event:"scroll",effect:"show",container:window};
		if(options){$.extend(settings,options);}
		
		var elements=this;
		if("scroll"==settings.event){
			$(settings.container).bind("scroll",
				function(event)
				{
					var counter=0;
					elements.each(
						function()
						{
							if(!$.belowthefold(this,settings)&&!$.rightoffold(this,settings))
							{
								$(this).trigger("appear");
							}else{
								if(counter++>settings.failurelimit)
								{
									return false;
								}
							}
						});
						var temp=$.grep(elements,
						function(element){
							return!element.loaded;
						});
						elements=$(temp);
					});
				}
		
					
		return this.each(
			function()
			{
				var self=this;
				if (undefined == $(self).attr("data-src")) {$(self).attr("data-src", $(self).attr("src"));}

				if("scroll"!=settings.event||$.belowthefold(self,settings)||$.rightoffold(self,settings))
				{
					if(settings.placeholder)
					{
						$(self).attr("src",settings.placeholder);
					}else{
						$(self).removeAttr("src");
					}
					self.loaded=false;
				}else{
					self.loaded=true;
				}
				$(self).one("appear",function()
				{
					if(!this.loaded){$("<img />").bind("load",
					function()
					{
						//$(self).hide().attr("src", $(self).attr("data-src"))[settings.effect](settings.effectspeed);
						$(self).attr("src", $(self).attr("data-src"))
						$(self).trigger("onload");
						self.loaded=true;
					}).attr("src",$(self).attr("data-src"));
				};
			});
					
			if("scroll"!=settings.event)
			{
				$(self).bind(settings.event,
				function(event)
				{
					if(!self.loaded)
					{
						$(self).trigger("appear");
					}
				});
			}
		});
	};
})(jQuery);
  
/* ---------------------------------- */

/* Worker */

(function($) {


    $.distancefromfold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return (fold + settings.threshold) - $element.offset().top ;
    };
    
    $.belowthefold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $element.offset().top - settings.threshold;
    };
        
    $.abovethetop = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $element.offset().top + settings.threshold  + $element.height();
    };
    
    $.inview = function($element, settings) {
        return ($.abovethetop($element,settings)!=true && $.belowthefold($element,settings)!=true)
    };
	
	$.extend($.expr[':'],{
		"below-the-fold":"$.belowthefold(a, {threshold : 0, container: window})",
		"above-the-fold":"!$.belowthefold(a, {threshold : 0, container: window})",
		"right-of-fold":"$.rightoffold(a, {threshold : 0, container: window})",
		"left-of-fold":"!$.rightoffold(a, {threshold : 0, container: window})"
	});
    
})(jQuery);  

/* ---------------------------------- */

/* Easing select *//*

(function($) {

$.fn.easingSelect = function(id) {
	var $this = $(this),
		easingFns = $.easing,
		$select = $('<select class="easing" id="'+id+'" />');
	
		for(var i in easingFns) {
			// def is the default easing fn and should be skipped
			if(i !== "def") {
				$select.append("<option>" + i + "</option>")
			}
		}
		$this.prepend($select);
		
	return $(this);
}

})(jQuery); 

/* ---------------------------------- */

/* Fancyboxes */

$(document).ready(function() {
	
	$("#nieuws a.more, #vacatures a.more").fancybox({
		'width'				: 800
	});
	
	$("a.popup").fancybox();
	
	$("#pers .contact-sheet a, a.gmaps, a.pdf").fancybox({
		'width'				: '70%',
		'height'			: '70%',
        'autoScale'     	: false,
		'type'				: 'iframe'
	});
	
	$(".video-galerij a").click(function() {
	$.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'			: 680,
			'height'		: 495,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
			   	 'wmode'		: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});

	return false;
	});
	
});

/* ---------------------------------- */
