/**
 * @author Edenspiekermann Amsterdam
 * @description	DEFAULT JAVASCRIPT Functions
 * 
 */

/* GLOBALS */
/* if (staticRootPath === undefined) { var staticRootPath = '..';  } */
/* load Javascript Enabled specific + sIFR heading styles */
/* $('<link rel="stylesheet" href="'+ staticRootPath +'/style/js-enabled.css" type="text/css" />').appendTo($('head')); */

/*NARCIS root remains the same*/
$('<link rel="stylesheet" href="/style/js-enabled.css" type="text/css" />').appendTo($('head'));

/*
 * configuration
 * 
 */
config = {
	
	easing			 : 	'easeOutQuad',						// easing method
	onHoverClassName :	'hover',							// classname added on mouseOver event
	debug			 : 	false,								// tracing debug information (true/false)
	maxListItems	 :	4,									// maximum number of visible list items in expandable lists
	expandableText	 : 'meer',								// linkable text to expand list
	inflateText	 	 : 'minder',							// linkable text to inflate list
	showMoreText	 : 'Toon samenvatting', 				// linkable text to show extra text in search-results list
	hideMoreText	 : 'Verberg samenvatting',				// linkable text to hide extra text in search-results list
	closeText		 : 'Sluiten',							// close text in popup lightbox layer
	ajaxErrorText	 : 'There was an error making the AJAX request.'
}	


/* at DOCUMENT READY initialize knaw object */
$(document).ready(function() {
	knaw.init();
	
	//Initialize the modalscreen layer for popups and overlays
	ModalScreen.init();
	popupLayer.init();
});


/* knaw object, contains all knaw default functionality */

knaw = {
	
	defaults: {
		
		easing: config.easing,
		
		setEasing: function()
		{			
			jQuery.easing.def = knaw.defaults.easing;
		},
		
		scrollToTop: function()
		{
			$('a[href*="#top"]').click(function()
				{
					$.scrollTo($('#start'), 300);
					
					return false;
				}
			);
		},
		
		openExternalLink: function()
		{
			$('a[rel="#nofollow"]').click(function()
				{
					window.open($(this).attr('href'));
					return false;	
				}
			);
		},
		
		hover: function(element, className)
		{
			if (className==null) className = config.onHoverClassName;
			$(element).hover(
				function()
				{
					$(this).addClass(className);
				},
				function (){
					$(this).removeClass(className);
				}
			);
		},			
		
		holdFieldValues: function()
		{
		  var elem = $('input:text');
		  if(elem.length != 0){
			$('input:text').each(function(){
				$(this).addClass('no-focus');
				var initValue = $(this).val();			
				
				if ( $(this).hasClass('label-value') ) {				
					var label = $(this).parent().find('label');
					$(label).addClass('text-only');
					$(this).val($(label).html());
					initValue = $(label).html();
				}
				
				if(initValue == '' || $(this).hasClass('hold-value') ) return;
				// onFocus remove default value + remove class no-focus
				$(this).focus(function(){
					$(this).removeClass('no-focus')
					if($(this).val() == initValue) $(this).val('');
						
				})
				// onBlur replace empty value with default value + add class no-focus
				$(this).blur(function(){				
					if ($(this).val() == '') {
						$(this).val(initValue);
						$(this).addClass('no-focus');
					}
				})
		  });
		  }
			$('textarea').each(function(){
				$(this).addClass('no-focus');
				var initValue = $(this).val();			
				if ( $(this).hasClass('label-value') ) {				
					var label = $(this).parent().find('label');
					$(label).addClass('text-only');				
					$(this).val($(label).html());
					initValue = $(label).html();
				}
				
				if(initValue == '' || $(this).hasClass('hold-value') ) return;
				// onFocus remove default value + remove class no-focus
				$(this).focus(function(){
					$(this).removeClass('no-focus')
					if($(this).val() == initValue) $(this).val('');
						
				})
				// onBlur replace empty value with default value + add class no-focus
				$(this).blur(function(){				
					if ($(this).val() == '') {
						$(this).val(initValue);
						$(this).addClass('no-focus');
					}
				})
			});
		},
		
		toggleList: function(targetClassName)
		{
			if (config.debug) alert( 'found items: ' + $('.'+targetClassName).length );			
		
			$('ul.'+targetClassName).each(function()
				{
					if ($(this).children('li').length < config.maxListItems ) return; 					
					$(this).addClass('has-more');
					$(this).children('li').each(function()
						{
							if ( $(this).parent('ul').children('li').index(this) > config.maxListItems-1 ) {
								$(this).addClass('hide');								
							}
						}
					);
					$('<li class="item-link"><a href="#" class="link-style01 toggle-expand">'+config.expandableText+'</a></li>').appendTo($(this));
						
				}
			);
			
			$('ul.'+targetClassName+' a.toggle-expand').click(function()
				{
					if (!$(this).parent().parent('ul.'+targetClassName).hasClass('open')) {
						// switch to open
						$(this).parent().parent('ul.'+targetClassName).addClass('open');
						$(this).parent().parent('ul.'+targetClassName).children('li').each(
							function()
							{								
								$(this).removeClass('hide');								
							}
						);
						$(this).html(config.inflateText);						
					} 
					else 
					{
						// switch to hide
						$(this).parent().parent('ul.'+targetClassName).removeClass('open');
						$(this).parent().parent('ul.'+targetClassName).children('li').each(function()
							{
								if ( $(this).parent('ul.'+targetClassName).children('li').index(this) > config.maxListItems-1 ) {
									if ($(this).hasClass('item-link') ) return;
									$(this).addClass('hide');								
								}
							}
						);
						$(this).html(config.expandableText);
					}
					
					return false;	
				}
			);
		},
				
		enableButtonHover: function() 
		{
			$('input[type="button"], input[type="submit"]').each(function()
				{
					knaw.defaults.hover($(this))	
				}
			);	
		},
		
		styleSelectBox: function()
		{
			
			if ($.browser.msie && $.browser.version=="6.0") return;
			
			if ($.browser.msie && $.browser.version=="7.0") {
				$('select.select-month, select.select-year').parent('div.row').addClass('special-row');	// prevent invisible overflow		
				$("select.select-month, select.select-year").selectbox({listboxMaxSize: '30', animationSpeed: 'fast'});
				return;
			}
			
			$('select.selectbox, select.select-month, select.select-year').parent('div.row').addClass('special-row');	// prevent invisible overflow			
			$("select.selectbox, select.select-month, select.select-year").selectbox({listboxMaxSize: '30', animationSpeed: 'fast'});
			
		}
		
	},
	
	init: function()
	{
		knaw.defaults.holdFieldValues();
		knaw.defaults.scrollToTop();
		knaw.defaults.openExternalLink();
		knaw.defaults.enableButtonHover();
		knaw.defaults.styleSelectBox();
		knaw.defaults.toggleList('expandable');
		
		
		//if (knaw.intranet != null) knaw.intranet.init();
		if (knaw.internet != null) knaw.internet.init();
	},
	
	/* INTERNET specific functionality */
	internet: {
		
		init: function()
		{
			var internet = knaw.internet;									// shortcut to knaw.internet object
			
			internet.addShadowContainer();
			internet.checkFont();	
			internet.toolTip();
			internet.dropDown();
			internet.expanderList('read-more');
		}, 
		addShadowContainer: function()
		{
			$('div#PageContainer').wrap($('<div id="ShadowContainer"></div>'))
		},
		
		checkFont: function()
		{
			detect = new Detector();
			var hasCambria = detect.test('Cambria');
			var hasCorbel = detect.test('Corbel');
			var isFirefoxWindows = $.browser.mozilla && $.client.os == 'Windows';
			var isLinux = $.client.os == 'Linux';
			
			$('link[@rel*=style][title]').each(function(i)
			{
				this.disabled = true;
				if (hasCambria && hasCorbel && !isFirefoxWindows && !isLinux) {
					if (config.debug) alert('switch to Alternate Stylesheet');
					if ($(this).attr('title') == 'altfonts') this.disabled = false;	
				}
				
			});	
		},
		
		/* ToolTip - adds a tooltip to span.glossary elements
		 * takes the text from the title attribute  and creates the following html:
		 * <div class="tooltip">
				<p>[title text]</p>
			</div>
		*/
		toolTip: function() 
		{
			if ($('span.explanation').length > 0) {
				$('span.explanation').hover(
					function(e){ 
						// get the text from the title and then clear it
						$toolText = $(this).attr('title');
						$(this).attr("title","");
						$(document.createElement("div")).attr("class","tooltip").prependTo("body"); 
						$(".tooltip").append("<p>" + $toolText + "</p>");
						$(".tooltip").css("left", e.pageX);
						$(".tooltip").css("top", e.pageY + 8);
					},
					function(){
						$(this).removeClass('gloss-over');
						$('.tooltip').remove(); 
						// put the text back in the title
						$(this).attr("title",$toolText);
					}
				);			
			}
		}, 
		
		dropDown: function() 
		{
			if (($('div.search-options').length > 0) || ($('div.home-options').length > 0)) {
				$('div.search-options ul, div.home-options ul').hide();
				
				$('div.search-options a:not(div.search-options ul li a), div.home-options a:not(div.home-options ul li a)').click(
					function() {
						return false;
					}
				);
				$('div.search-options, div.home-options').hover(
					function() {
						$('div.search-options ul, div.home-options ul').show();
					}, 
					function() {
						$('div.search-options ul, div.home-options ul').hide();
					}
				);
			}
		}, 
		
		expanderList: function(targetClassName)
		{
			if (config.debug) alert( 'found items: ' + $('.'+targetClassName).length );			
			$('div.'+targetClassName).each(function()
				{
					$(this).hide();
					$('<span class="show-more">'+config.showMoreText+'</span>').appendTo($(this).parent());
					$('<span class="hide-more">'+config.hideMoreText+'</span>').appendTo($(this).parent());
					$('span.hide-more').hide();
				}
			);
			$('span.show-more, span.hide-more').hover(function()
				{
					$(this).addClass('hover');
				},
				function() {
					$(this).removeClass('hover');
				}
			);			
			$('span.show-more').click(function()
				{
					$(this).parent().find('div.' + targetClassName).show();
					$(this).parent().find('span.hide-more').show();
					$(this).hide();
				}
			);
			$('span.hide-more').click(function()
				{
					$(this).parent().find('div.' + targetClassName).hide();
					$(this).parent().find('span.show-more').show();
					$(this).hide();
				}
			);
		}
	}
}
/**
  * ModalScreen
  * @descr Create ModalScreen
  * 
  */
ModalScreen = {
	init:function(){
		if($('#ModalScreen').length>0) return;
		
		//create modal screen
		if($('#ModalScreen').length == 0){
			$('body').append('<div id="ModalScreen"></div>');		
		} 
		//create iframe mask
		if($('#ModalMask').length == 0) $('body').append('<iframe id="ModalMask" src="/images/fake-src.gif"></iframe>');
		
	},
	// size the modalscreen according to browserwindow's height and width
	sizing:function(){
				
		var h = $(window).height()>=$('#PageContainer').height() ? $(window).height() : $('#PageContainer').height();
				
		if($('#OverlayFrame').length>0){
			h = h >=($('#OverlayFrame').height()) ? h : ($('#OverlayFrame').height());
		}
		$('#ModalScreen').height(h+150);
		$('#ModalMask').height(h);
		
		var w = $(window).width()>=$('#PageContainer').width() ? $(window).width() : $('#PageContainer').width();
		$('#ModalScreen').width(w);
		$('#ModalMask').width(w);
	},
	show:function(){
		ModalScreen.init();
		ModalScreen.sizing();
		if(!(jQuery.browser.msie && jQuery.browser.version < 7)) $('#ModalScreen').css({opacity:'0'});
		$('#ModalMask').show();		
		$('#ModalScreen').show();
		if(!(jQuery.browser.msie && jQuery.browser.version < 7)) $('#ModalScreen').stop().animate({opacity:'0.5'},{ duration: 500, easing: 'easeInExpo'});
		$(window).bind("resize", function(){
			ModalScreen.sizing();
		});
	},
	hide:function(){	
		if(jQuery.browser.msie && jQuery.browser.version < 7){
			$('#ModalScreen').hide(); $('#ModalMask').hide();
		} 
		else $('#ModalScreen').stop().animate({opacity:'0'},{ duration: 300, easing: 'easeInExpo', complete:function(){$('#ModalScreen').hide(); $('#ModalMask').hide();}});		
		
		$(window).unbind("resize", function(){
			ModalScreen.sizing();
		});
	},
	//Show without animation (for example when an iframe is being loaded otherwise animation can get clunky)
	immediateShow:function(){
		ModalScreen.init();
		ModalScreen.sizing();
		$('#ModalMask').show();		
		$('#ModalScreen').show();
		$(window).bind("resize", function(){
			ModalScreen.sizing();
		});
	},
	//Hide without animation (for example when browserwindow is being resized)
	immediateHide:function(){
		$('#ModalScreen').hide(); 
		$('#ModalMask').hide();
		$(window).unbind("resize", function(){
			ModalScreen.sizing();
		});
	}
}
/*
 * popupLayer
 *  pops up a lightbox modal layer and loads an external div
 *  link syntax is as follows: <a href="staticPage.html#name-of-div" class="pu-layer">link</a>
 * 
 */
popupLayer = {
	visible:false, //true if .popup is visible
	init: function() {
		if ($('.pu-layer').length > 0) {
			$('.pu-layer').click(function() {
				popupLayer.show($(this));
				return false;	
			});
			
			$('#ModalScreen').click(function(){
				if(popupLayer.visible) popupLayer.hide();
			});	
		}
	},
	show:function(link){
		popupLayer.visible = true;
		ModalScreen.show();				
		// extract external filename from classname
		$externalPage = link.attr('class') + ".html";	
		
		// create div container
		if (link.attr('class').indexOf('wide') != -1) {
			$('body').append('<div class="popup wide"><div class="popup-content"></div></div>');
		}
		else {
			$('body').append('<div class="popup"><div class="popup-content"></div></div>');
		}	
				
		//If not IE6 set opacity to '0' so popup can fade in
		if(!(jQuery.browser.msie && jQuery.browser.version < 7)) $('.popup').css({opacity:'0'});
		
		//Position popup
		var x = ($(window).width()-$('.popup').width())/2;
		var y = $(window).scrollTop()>80 ? 20 +$(window).scrollTop() : 80;
		$('.popup').css({left:x+'px',top:y+'px'});
		
		//If not IE6 Fade in popup
		if(!(jQuery.browser.msie && jQuery.browser.version < 7)) $('.popup').animate({opacity:'1'},{ duration: 600, easing: 'easeInExpo'});
				
		/* image is already preloaded in page initalization */
		//$('#ContactPopUp .popup-content').html('<img class="loading" src="/images/icons/icon-loader.gif" />');
			
		// extract url from id
		$externalPage = link.attr('href');
		
		// Get our external div to be loaded:
		$linkArray = $externalPage.split('#');
		
		$externalPage = $linkArray[0];
		$externalDiv = $externalOption = '';
		if ($linkArray.length >= 2){
			$externalDiv = $linkArray[1];
			if ($linkArray.length >= 3){ //options index found
				$externalOption = $linkArray[2];
			}
		}
		
		// separate the id with a space and a comma	(to indicate the div to be loaded...)	
		//$externalPage = $externalPage.replace('#',' ,#');
		$externalPage = $externalPage+' ,#'+$externalDiv
		
		// load the external div into .popup .popup-content
		$('.popup .popup-content').load($externalPage, "",
		function(responseText, textStatus, XMLHttpRequest) {
           	if(textStatus == 'error') {
           	    $('.popup .popup-content').html('<div class="ajax-error">'+config.ajaxErrorText+'</div>');
           	}
			else {
				// loading is successful, so create close button
				$('.popup-content').append('<span class="pop-close">'+config.closeText+'</span>');
				// add behaviour to close button
				$('.pop-close').hover(function(){
					$(this).addClass('hover');
				}, function(){
					$(this).removeClass('hover');		
				});
				
				$('.pop-close').click(function(){
					popupLayer.hide();		
					return false;
				});
				// any functions required for the content in the popup need to be called again here!
				if ($externalDiv == 'show-tree'){					
					//add js:
					$.getScript('/js/lib/mktree.js', function() {
  						convertTrees();
					});
				}
			}
        });
	},
	hide:function(){
		popupLayer.visible = false;		
		ModalScreen.immediateHide();
		$('.popup').remove(); 	
	}
}
/**
 * @descr Window resize events
 */
$(window).resize(function(){
  popupLayer.hide();
});
