/**
 * @author Edenspiekermann Amsterdam
 * @description	DEFAULT JAVASCRIPT Functions
 * 
 */

/* GLOBALS */
if (staticRootPath === undefined) { var staticRootPath = '..';  }



/*
 * configuration
 * 
 */
config = {
	
	easing			  : 'easeOutQuad',						// easing method
	onHoverClassName  :	'hover',							// classname added on mouseOver event
	debug			  : false,								// tracing debug information (true/false)
	maxListItems	  :	10,									// maximum number of visible list items in expandable lists
	expandableText	  : 'meer',								// linkable text to expand list
	inflateText	 	  : 'minder',							// linkable text to inflate list
	carrousselTimeout : 15 //seconds
}	


/* at DOCUMENT READY initialize knaw object */
/* document ready is way too slow in IE
*$j(document).ready(function() {
*	knaw.init();
*});
*/

var alreadyrunflag=0;

if (document.addEventListener)
  document.addEventListener("DOMContentLoaded", function(){alreadyrunflag=1; knaw.init();}, false);
else if (document.all && !window.opera){
  document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
  var contentloadtag=document.getElementById("contentloadtag");
  contentloadtag.onreadystatechange=function(){
    if (this.readyState=="complete"){
      alreadyrunflag=1;
      knaw.init();
    }
  }
}

window.onload=function(){
  setTimeout("if (!alreadyrunflag){knaw.init();}", 0);
}


function Carroussel(element) {
	var domElement = $j(element);
	var cItems = domElement.find(".inter_carroussel_item");
	var cBtns = domElement.find(".inter_carroussel_nav li a");
	var activeIndex = 0;
	
	function changeState(activeIndex, currentIndex) {
		cItems.eq(currentIndex).fadeIn(800);
		cBtns.each(function(index, element){$j(element).removeClass("inter_btn_active")});
		cBtns.eq(currentIndex).addClass("inter_btn_active");
	};

	if (cItems.length > 1) {
		cItems.each(function(index, elem) {
			if (!$j(elem).hasClass("inter_hidden")) {
				activeIndex = index;
			}
		});
		
		domElement.find(".inter_btn.inter_carroussel_prev, .inter_btn.inter_carroussel_next").click(function() {
			cItems.eq(activeIndex).fadeOut(800);
			var currentIndex;
			
			if ($j(this).hasClass("inter_carroussel_prev")) {
				if (activeIndex <= 0) {
					activeIndex = cItems.length;
				}				
				currentIndex = activeIndex - 1;
			}
			else {
				if (activeIndex == cItems.length-1) {
					activeIndex = -1;
				}				
				currentIndex = activeIndex + 1;	
			}
			
			changeState(activeIndex, currentIndex);
			activeIndex = currentIndex;						
			knaw.inter.startAutomaticTransition();
			
			return false;
		});
		
		cBtns.each(function(index, navBtn) 
	    {
			if ($j(navBtn).hasClass("inter_btn_active")) {
				activeIndex = index;
			}				
			
			$j(navBtn).click(function(event)
			{
				if (index == activeIndex) {
					return false;
				}
				
				cItems.eq(activeIndex).fadeOut(800);
				changeState(activeIndex, index);
				activeIndex = index;
				knaw.inter.startAutomaticTransition();
				
				return false;					
			});				
	    });
		
		knaw.inter.startAutomaticTransition();
	}
	else {
		var heightNoBtns = parseInt(domElement.css("height"))-20;
		domElement.css("height", heightNoBtns+"px").find(".inter_btn.inter_carroussel_prev, .inter_btn.inter_carroussel_next").remove();
		cBtns.parents(".inter_carroussel_nav").remove();
	}
}


/* knaw object, contains all knaw default functionality */

knaw = {
	
	defaults: {
		
		easing: config.easing,
		
		setEasing: function()
		{			
			jQuery.easing.def = knaw.defaults.easing;
		},
		
		scrollToTop: function()
		{
			$j('a[href="#top"]').click(function()
				{
					$.scrollTo(0, 300);
					
					return false;
				}
			);
		},
		
		openExternalLink: function()
		{
			$j('a[rel="nofollow"], a[rel="external"]').click(function()
				{
					$j(this).attr("target", "blank");
				}
			);
		},
		
		hover: function(element, className)
		{
			if (className==null) className = config.onHoverClassName;
			$j(element).hover(
				function()
				{
					$j(this).addClass(className);
				},
				function (){
					$j(this).removeClass(className);
				}
			);
		},			
		
		holdFieldValues: function()
		{
			$j('input:text').each(function(){
				$j(this).addClass('no-focus');
				var initValue = $j(this).val();			
				
				if ( $j(this).hasClass('label-value') ) {				
					var label = $j(this).parent().find('label');
					$j(label).addClass('text-only');
					$j(this).val($j(label).html());
					initValue = $j(label).html();
				}
				
				if(initValue == '' || $j(this).hasClass('hold-value') ) return;
				// onFocus remove default value + remove class no-focus
				$j(this).focus(function(){
					$j(this).removeClass('no-focus')
					if($j(this).val() == initValue) $j(this).val('');
						
				})
				// onBlur replace empty value with default value + add class no-focus
				$j(this).blur(function(){				
					if ($j(this).val() == '') {
						$j(this).val(initValue);
						$j(this).addClass('no-focus');
					}
				})
			});
			$j('textarea').each(function(){
				$j(this).addClass('no-focus');
				var initValue = $j(this).val();			
				if ( $j(this).hasClass('label-value') ) {				
					var label = $j(this).parent().find('label');
					$j(label).addClass('text-only');				
					$j(this).val($j(label).html());
					initValue = $j(label).html();
				}
				
				if(initValue == '' || $j(this).hasClass('hold-value') ) return;
				// onFocus remove default value + remove class no-focus
				$j(this).focus(function(){
					$j(this).removeClass('no-focus')
					if($j(this).val() == initValue) $j(this).val('');
						
				})
				// onBlur replace empty value with default value + add class no-focus
				$j(this).blur(function(){				
					if ($j(this).val() == '') {
						$j(this).val(initValue);
						$j(this).addClass('no-focus');
					}
				})
			});
		},
		
		toggleList: function(targetClassName)
		{
			if (config.debug) alert( 'found items: ' + $j('.'+targetClassName).length );			
		
			$j('ul.'+targetClassName).each(function()
				{
					if ($j(this).children('li').length < config.maxListItems ) return; 					
					$j(this).addClass('has-more');
					$j(this).children('li').each(function()
						{
							if ( $j(this).parent('ul').children('li').index(this) > config.maxListItems-1 ) {
								$j(this).addClass('hide');								
							}
						}
					);
					$j('<li class="item-link"><a href="#" class="link-style01 toggle-expand">'+config.expandableText+'</a></li>').appendTo($j(this));
						
				}
			);
			
			$j('ul.'+targetClassName+' a.toggle-expand').click(function()
				{
					if (!$j(this).parent().parent('ul.'+targetClassName).hasClass('open')) {
						// switch to open
						$j(this).parent().parent('ul.'+targetClassName).addClass('open');
						$j(this).parent().parent('ul.'+targetClassName).children('li').each(
							function()
							{								
								$j(this).removeClass('hide');								
							}
						);
						$j(this).html(config.inflateText);						
					} 
					else 
					{
						// switch to hide
						$j(this).parent().parent('ul.'+targetClassName).removeClass('open');
						$j(this).parent().parent('ul.'+targetClassName).children('li').each(function()
							{
								if ( $j(this).parent('ul.'+targetClassName).children('li').index(this) > config.maxListItems-1 ) {
									if ($j(this).hasClass('item-link') ) return;
									$j(this).addClass('hide');								
								}
							}
						);
						$j(this).html(config.expandableText);
					}
					
					return false;	
				}
			);

			
			
		},
		
		enableButtonHover: function() 
		{
			$j('input[type="button"], input[type="submit"]').each(function()
				{
					knaw.defaults.hover($j(this))	
				}
			);	
		},
		
		styleSelectBox: function()
		{
			
			if ($j.browser.msie && $j.browser.version=="6.0") return;
			
			if ($j.browser.msie && $j.browser.version=="7.0") {
				$j('select.select-month, select.select-year, select.inter_select_nav_elem').parent('div.row').addClass('special-row');	// prevent invisible overflow		
				$j("select.select-month, select.select-year, select.inter_select_nav_elem").selectbox({listboxMaxSize: '30', animationSpeed: 'fast'});
				return;
			}
			
			$j('select.selectbox, select.select-month, select.select-year, select.inter_select_nav_elem').parent('div.row').addClass('special-row');	// prevent invisible overflow			
			$j("select.selectbox, select.select-month, select.select-year, select.inter_select_nav_elem").selectbox({listboxMaxSize: '30', animationSpeed: 'fast'});
		}
	},
	
	inter:
	{
		automaticTransition: false,

	    enableCarroussel: function ()
	    {
			var carroussels = $j(".inter_carroussel");
			carroussels.each(function(index, element)
			{
				var carr = Carroussel(element);
			});
	    },
	    
	    startAutomaticTransition: function()
	    {
			if ($j(".inter_carroussel.inter_home").length === 0) {
				return;
			}

	    	if (knaw.inter.automaticTransition !== false) {
	    		window.clearInterval(knaw.inter.automaticTransition);
	    		knaw.inter.automaticTransition = false;
	    	}
	    	
	    	knaw.inter.automaticTransition = window.setInterval("$j('.inter_btn.inter_carroussel_next').trigger('click')", config.carrousselTimeout * 1000);
	    }
	},
	
	init: function()
	{
		knaw.defaults.holdFieldValues();
		knaw.defaults.scrollToTop();
		knaw.defaults.openExternalLink();
		knaw.defaults.enableButtonHover();
		knaw.defaults.styleSelectBox();
		knaw.defaults.toggleList('expandable');
		
		knaw.inter.enableCarroussel();
		knaw.intranet.init();
	},
	
	/* INTRANET specific functionality */
	intranet: {
		
		init: function()
		{
			var intranet = knaw.intranet;									// shortcut to knaw.intranet object
			
			knaw.defaults.hover( $j('div#Navigation ul#SiteNav > li') );
			intranet.addShadowContainer();
			intranet.checkFont();
			intranet.tabsNav();
			intranet.toggleMediaBox();
			intranet.showToolTip();	
			//$('div#PageContainer').css('display','block');
		},
		addShadowContainer: function()
		{
			$j('div#PageContainer').wrap($j('<div id="ShadowContainer"></div>'))
		},
		checkFont: function()
		{
			detect = new Detector();
			var hasCambria = detect.test('Cambria');
			var hasCorbel = detect.test('Corbel');
			var isFirefoxWindows = $j.browser.mozilla && $j.client.os == 'Windows';
			
			$j('link[@rel*=style][title]').each(function(i)
			{
				this.disabled = true;
				if (hasCambria && hasCorbel && !isFirefoxWindows) {
					if (config.debug) alert('switch to Alternate Stylesheet');
					if ($j(this).attr('title') == 'altfonts') this.disabled = false;	
				}
				
			});
				
			
		},
		tabsNav: function()
		{
			// only do this when there is a classname 'on' on the tabs-nav div
			if ( $j('.tab-navigation').hasClass('on') ) {
				
				// hide h2 headers in tab-content-blocks
				$j('.tab-content h2').addClass('text-only')

				// get id name of active item
				var activeID = $j('.tab-navigation .active').attr('id');
				// adjust name to get content id
				var activeTabContent = activeID.replace("tn-","")
				// add class hide to other tab content divs
				$j('.tab-content').not('#'+activeTabContent).addClass('hide');
				// add toggle to nav links
				$j('.tab-navigation a').click(function() {
					$j('.tab-navigation .active').removeClass('active')
					$j(this).parent().addClass('active')
					var thisID = $j(this).parent().attr('id');
					var newActiveTabContent = thisID.replace("tn-","")
					$j('#'+newActiveTabContent).removeClass('hide')
					$j('.tab-content').not('#'+newActiveTabContent).addClass('hide');
					return false;
				});
			
			} else {
				return false;
			}
			// end if
		},
		toggleMediaBox: function()
		{
			// set max number of media items to show
			var maxMediaItems = 3;
			$j('.media-block.hasmore').each(function() {
				var numMediaItems = $j(this).find('a.media').length;
				if (numMediaItems > maxMediaItems) { showMoreLink = "yes"; } else { return true;}
				// count is 0
				itemcount = 0;
				$j(this).find('a.media').each(function() {
					itemcount++;
					//alert(itemcount);
					if (itemcount > maxMediaItems) {
						$j(this).parent().addClass('hide')
					}
				});
				// show toon alles link
				if (showMoreLink == "yes") {
					$j('<a href="#" class="media-toggle showmore">Toon alles +</a></li>').appendTo($j(this));
				} else { return false;}
				
			});
			// toggle link
			$j('.media-toggle').each(function() {
				$j(this).toggle(function() {
					// unhide
					$j(this).parent().find('.hide').addClass('parked');					
					$j(this).parent().find('.hide').removeClass('hide');
					// change text of toggle link
					$j(this).text('Toon minder -');			
				},
				function() {
					// hide 
					$j(this).parent().find('.hide').removeClass('parked');
					$j(this).parent().find('.parked').addClass('hide');
					$j(this).text('Toon alles +');					
				});
			});
		},
		showToolTip: function()
		{
			// only do this when there are elements with classname 'tooltip' on the page
			// otherwise this will generate an error message.
			var numToolTips = $j('a.tooltip').length;
			if (numToolTips > 0) {
				$j('a.tooltip').tooltip({
					showURL: false,
					fixPNG: true
				});
			} else {
				return true;
			}
		}
	}
	
}


$j(document).ready(function() {
	$j("a.inter_toggle_more").toggle(
		function() { 
			$j(this).prev().toggle(150, function() {
				if ($.browser.msie) {
					$j(this).get(0).style.removeAttribute("filter");
				}
			});
			$j(this).attr("class", "inter_toggle_less").text("Toon minder");
		},
		function() {
			$j(this).prev().toggle(150, function() {
				if ($.browser.msie) {
					$j(this).get(0).style.removeAttribute("filter");
				}
			});
			$j(this).attr("class", "inter_toggle_more").text("Toon meer");
		}
	);
	
	/**
	 * Add form field button
	 * 
	 * Capture click on link for adding an extra field to a form. Clicking 
	 * clones the last of a set of matching elements (only input fields of
	 * type 'text' and 'file' as well as textareas can be added. The added
	 * field gets the same id as the original field appended with a 
	 * zero-based integer.
	 * If the anchor with class 'form_btn_remove_field' is there but is not 
	 * visible, it's display property is set to 'inline-block'
	 */
	$j("a.form_btn_add_field").click(function() {
		var allowedNumberOfClones = 9;
		var cloneId;
		var numberOfClones;
		var cloneParent = $j('#cloneparent');
		
		var clone = cloneParent.clone();
		
		//count all clones and generate the new clone's id to create the names and classes
		numberOfClones = $j('div.clone').size();
		cloneId = numberOfClones + 2;
		clone.attr('id','clone' + cloneId);
		
		if(cloneId > allowedNumberOfClones ){
			if(cloneId > allowedNumberOfClones + 1){
				return false;
			} else {
				$j('.form_btn_add_field').addClass('disabled');
			}
		} 

		clone.children('label').attr('for','email_form_receiver_'+cloneId);
		clone.children('label').children('span').remove();
		clone.children('label').append(cloneId);
		clone.children('input').attr('id','email_form_receiver_'+cloneId);
		clone.children('input').attr('value','');
		
		clone.addClass('clone');
		//place the new cloned row before the add button
		$j(this).before(clone);
		
		//reposition the form
		positionEmailForm();
				
		return false;
	});
	
	$j('#Footer .inter_forward_page').click(function(){
		$j('#email_form_block').css('display','block');
		return false;
	});
	
	$j('.email_form_close').click(function(){
		$j('#email_form_block').css('display','none');
		positionEmailForm();
		return false;
	});
	
	
	positionEmailForm();
	
	function positionEmailForm(){
		$j('#email_form_block').css('bottom', ($j('#email_form_block').height() + 50) + 'px');
	}
});

