/*
	graphical user interface scripts

*/

if (document.addEventListener) 
{
    document.addEventListener("DOMContentLoaded", init, null);
}

// fallback
window.onload = init;

function init()
{
	//make sure we only get here once
	if (arguments.callee.done)
	{
		return;
	}
	arguments.callee.done = true;
	
	add_events_links();
	add_click_searchbox();
		
	//attachBalloons();
	//attachFilterEvents();
	replaceMedia();
	attachClientView();
	
	searchForMovie();
	initFancyBox();
		
	startGlider();
	placeReadspeaker();
	setHeading();
	shuffleCloud();
}

function add_events_links()
{
	var links = document.getElementsByTagName('a');
	var img = '&nbsp;<img src="/style/images/icons/newwindow.png" alt="(Deze link opent in een nieuw venster)" />';
	for (var i = 0; i < links.length; i++)
	{
		if (links[i].className.indexOf('preparsed') == -1)
		{
			switch (links[i].className)
			{
				case 'newwindow':
					links[i].setAttribute('title', links[i].getAttribute('title') + ', opent in een nieuw venster.');  
					links[i].onclick = newwin;
					links[i].innerHTML = links[i].innerHTML + img;
					break;
			}
		}
	}
}

function initFancyBox()
{
	$("a.gallery").each(function(key, value)
	{
		$(value).attr('rel','aap');
	});
	
	$("a.gallery").fancybox({
		'type'	: 'image',
		'titleShow' : true,
		'transitionIn' : 'fade',
		'transitionOut' : 'fade'
	});
}

function newwin()
{
	window.open(this.href,'_blank');
	return false;
}

function add_click_searchbox()
{
	set_click('q');
	set_click('sq');
	set_click('qs');
	set_click('search_text');
	set_click('zoeken');
}

function set_click(id)
{
	var s_box = document.getElementById(id);
	if (s_box)
	{
		s_box.onclick = function(){clear_sbox(this)};
	}
}

function clear_sbox(a_box)
{
	if (a_box.value == 'Zoeken op deze site')
	{
		a_box.value = '';
	}
	if (a_box.value == 'Uw zoekopdracht')
	{
		a_box.value = '';
	}
}

/* ----- ---- - --- -- -- - ----- -- --- - ---- - -*/

function set(id,display)
{
	var obj	=	document.getElementById(id);
	if(obj)
	{
		obj.style.display	=	display;
	}
}

/* ----- ---- - --- -- -- - ----- -- --- - ---- - -*/

function prepare_menu()
{
	var menu = document.getElementById('subnavlist')
	if (menu)
	{
		collapse_all(menu);
		open_selected(menu);
		apply_events(menu);
	}
}

function toggle(a_item, docollapse)
{
	var uls = a_item.getElementsByTagName('ul')[0];
	var a = a_item.getElementsByTagName('a')[0];

	if (a.href == 'javascript:void(0)')
	{
		if (uls.style.display == 'none' || uls.style.display == '')
		{
			uls.style.display = 'block';
			a_item.className = 'opened';
		}
		else if (docollapse)
		{
			uls.style.display = 'none';
			a_item.className = 'closed';
		}
	}
}

function collapse_all(menu)
{
	var uls = menu.getElementsByTagName('ul');
	for (var n = 0; n < uls.length; n++)
	{
		uls[n].style.display = 'none';
	}
}

function open_selected(menu)
{
	var lis = menu.getElementsByTagName('li');
	var loc = String(document.location);
	for (var n = 0; n < lis.length; n++)
	{
		var href = lis[n].getElementsByTagName('a')[0];
		if (href == loc)
		{
		
			href.className = 'selected';
			p = lis[n].parentNode;

			// open all parents
			while(p.getAttribute('id') != 'subnavlist')
			{
				if (p.className == 'closed')
				{
					p.className = 'opened';
				}
				if (p.className ==  'folder index')
				{
					p.className = p.className + ' opened';
				}
				p.style.display='block';
				p = p.parentNode;
			}
			
			// open children
			ul = lis[n].getElementsByTagName('ul')[0];
			if (ul)
			{
				ul.style.display = 'block';
			}
			break;
		}
	}

}


function apply_events(menu)
{
	var lis = menu.getElementsByTagName('li');
	for (var n = 0; n < lis.length; n++)
	{
		if (lis[n].getElementsByTagName('ul').length > 0)
		{
			a = lis[n].getElementsByTagName('a')[0];
			if (lis[n].className.indexOf('index') == -1)
			{
				a.setAttribute('href','javascript:void(0)');
			}
			if (lis[n].className.indexOf('opened') == -1)
			{
				lis[n].className = 'closed';
			}
			// nasty, but neccesary for IE...
			a.onclick = function()
						{
							toggle(this.parentNode.parentNode,true)
						};
			
			// make sure people using a keyboard can access the links
			a.onkeyup = function()
						{
							toggle(this.parentNode.parentNode,false)
						};
		}
	}
}

function setfocus(id)
{
	var field = document.getElementById(id);
	if (field)
	{
		field.focus();
		flash(id, 1);
	}
}

function flash (id, pass)
{
	var field = document.getElementById(id);
	border = '2px solid red';
	if (pass % 2 == 0)
	{
		border = '2px dashed white';
	}
	field.style.border = border;
	if (pass < 15)
	{
		pass ++
		setTimeout("flash('" + id+ "','" + pass + "')",50);
	}
}

function hide_reactform()
{
	if(String(document.location).indexOf('eageer/') == -1)
	{
		var obj	=	document.getElementById('reactform');
		if(obj)
		{
			obj.style.display	=	'none';
		}
	}
}

function show_reactform()
{
	var obj	=	document.getElementById('reactform');
	if(obj)
	{
		if(obj.style.display == 'block')
		{
			hide_reactform();
		}
		else
		{
			obj.style.display	=	'block';
		}
	}
}

/* ----- ---- - --- -- -- - ----- -- --- - ---- - -*/

function hilite_table()
{
	if(document.getElementById && document.createTextNode)
 	{
   		var tables	=	document.getElementsByTagName('table');
   		for (var i=0;i<tables.length;i++)
   		{
    		if(tables[i].className=='hilite')
    		{
     			var trs=tables[i].getElementsByTagName('tr');
     			for(var j=0;j<trs.length;j++)
     			{
					if(trs[j].parentNode.nodeName=='TBODY' && trs[j].parentNode.nodeName!='TFOOT')
					{
						trs[j].onmouseover=function()
						{
							this.className += ' active';
							return false;
						}
       					trs[j].onmouseout=function()
       					{
       						this.className = this.className.replace(/active/g,'');
       						return false;
       					}
     				}
    			}
   			}
  		}
 	}
}

/* -----------------------------------------*/
function add_onclick_notities()
{
	//vergadering omzetten naar Ajax
	if(document.getElementById('title_note_icon'))
	{
		var vergaderinglink = $('title_note_icon').down('a');
		if(vergaderinglink != null)
		{
			vergaderinglink.onclick=function()
				{
					var id	=	this.getAttribute('id').replace(/notelink/g,'');
					if(id != "")
					{
						var idx	=	id.split('_');
						get_note(idx[0],idx[1],idx[2]);
					}
				}
			vergaderinglink.setAttribute('href','javascript:void(0)');
		}
	}
	//voor documenten
	if(document.getElementById('notitie') != null)
	{
		var docelement = $('notitie').down('div');
		if(docelement !=null)
		{
			var id = docelement.getAttribute('id').replace(/note/g,'');
			if(id != "")
			{
				var idx	=	id.split('_');
				update_note_links(idx);
			}
		}
	}
}

/* ----- ---- - --- -- -- - ----- -- --- - ---- - -*/

function add_onclick_meeting()
{
	var tables	=	document.getElementsByTagName('table');
	
	for (var i=0;i<tables.length;i++)
	{
		if(tables[i].className=='hilite')
		{
 			var trs=tables[i].getElementsByTagName('tr');
 			for(var j=0;j<trs.length;j++)
 			{
 				if(trs[j].parentNode.nodeName=='TBODY' && trs[j].parentNode.nodeName!='TFOOT')
				{
					var id		=	trs[j].getAttribute('id');
					if(id.indexOf('agendapunt') != -1)
					{
						var as	=	trs[j].getElementsByTagName('A');
						for(var k=0;k < as.length;k++)
						{
							var asid = as[k].getAttribute('id');
							if(null != asid && asid.indexOf('notelink') != -1)
							{
								as[k].onclick=function()
								{
									var id	=	this.getAttribute('id').replace(/notelink/g,'');
									var idx	=	id.split('_');
									get_note(idx[0],idx[1],idx[2]);
								}
							}
							else
							{
								as[k].onclick=function()
								{
									var id	=	this.parentNode.parentNode.id;
									var id	=	id.replace(/agendapunt/g,'');
									var idx	=	id.split('_');
									set_active(idx[0],idx[1],true);
									//move_sidebar_verg(this.parentNode);
								}
							}
							as[k].setAttribute('href','javascript:void(0)');
						}
					}
				}
 			}
 		}
 	}
}


function move_sidebar_verg(clicked)
{
	var sbar = $('sidebar_verg');
	var xy = Position.cumulativeOffset(clicked);
	
	var newy = xy[1] - 9;
	//verschillende browsers zijn het niet eens over
	//de positie...
	if (BrowserDetect.browser == 'Explorer')
	{
		// NOTE: gebruik dit soort code alleen als je
		// weet wat je doet. Over het algemeen wil
		// je namelijk testen op functionaliteit, niet
		// op versie. 
		if (BrowserDetect.version == 6)
		{
			newy -= 7; 
		}
		else if (BrowserDetect.version == 7)
		{
			newy -= 20;
		}
	}
	
	// afhankelijk van de vormgeving hier
	// 'paddingTop', 'marginTop' of, bij absolute 
	// positionering, 'top' gebruiken
	sbar.style.marginTop = newy - 203 + 'px';	
}

/* ----- ---- - --- -- -- - ----- -- --- - ---- - -*/

function focus_login()
{
	var obj	=	document.getElementById('name');
	if (obj)
	{
		setfocus_only('name');
	}
}

function setfocus_only(id)
{
	var field = document.getElementById(id);
	if (field)
	{
		field.focus();
	}
}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

//Functie: vervangt alle '&amp;' door eenn '&'. s = string met tekens
function replaceAmp( s ){
	s = s.replace( /&amp;/g, "&" );
	return s;
}

/*
############################################
####									####
####	Mediabox						####
####	( Vervangen thumbnails )		####
####									####
############################################
*/

function replaceMedia(){
	if( document.getElementById ){
		
		if( document.getElementById("mediaBox")){
		
			var box = document.getElementById( "mediaBox" );
			
			var list = box.getElementsByTagName( "span" );
			for( var i=0; i<list.length; i++ ){
				if( list[i].id != "movieBox" ){
					
					var c = list[i].className.split( " " );
					var t = c[(c.length-1)];
					
					replaceMediaThumbs( list[i] , t )
					
					
				}
			}
		}
	}
}

function replaceMediaThumbs( d , t ){
	var im = d.getElementsByTagName( "img" )[0];
	var s = im.src;
	d.style.background = "url('" + s + " ') center center";
	
	var ext = ".png";
	
	/* IE6 Check */
	var browser=navigator.appName;
	var b_version=navigator.userAgent;
	var MSIEOffset = b_version.indexOf("MSIE ");
	var version=parseFloat(b_version.substring(MSIEOffset + 5, b_version.indexOf(";", MSIEOffset)));
	
	if ((browser=="Microsoft Internet Explorer")  && (version <= 6)){
		ext = ".gif";
	}
	
	if( t == "audio" ){
		im.src = "/style/images/ta" + ext;
	} else if ( t == "video" ){
		im.src = "/style/images/tv" + ext;
	}
	
}

/*
############################################
####									####
####	Tekstballonnen					####
####	( In Footer, bij adres )		####
####									####
############################################
*/

function attachBalloons(){
	var lijst = new Array ( "GO" , "ZO" , "NIC" );
	if(document.getElementById){
		for( var i=0; i<lijst.length; i++ ){
			var btn = document.getElementById( lijst[i] );
			
			if(btn.addEventListener){
				btn.addEventListener( "mouseover" , function(evt)
				{
					if (evt.preventDefault) {
						evt.preventDefault();
						show( this.id , lijst );
						return false;
				}}, false );
				btn.addEventListener( "mouseout" , function(evt)
				{
					if (evt.preventDefault) {
						evt.preventDefault();
						hide( lijst );
						return false;
				}}, false );
			} else {
				btn.attachEvent ( "onmouseover" , function()
				{
					var b = event.srcElement.parentNode.id;
					show( b , lijst );
					return false;
				} );
				btn.attachEvent ( "onmouseout" , function(evt)
				{ 
					hide( lijst );
					return false;
				} );
			}		
		}
	}
}

function show( b , l){	
	for( var i=0; i<l.length; i++ ){
		t = document.getElementById( ("blok_" + l[i]) );
		if( b == l[i] ){
			t.style.display = "block";
		} else {
			t.style.display = "none";
		}
	}
}

function hide( l){	
	for( var i=0; i<l.length; i++ ){
		t = document.getElementById( ("blok_" + l[i]) );
		t.style.display = "none";
	}
}


/*
############################################
####									####
####	Plaatsen mediabox				####
####	( alleen op home)				####
####									####
############################################
*/
//Functie, kijkt of er een link is met de het id:movie zowja, wordt deze vervangen door een player
function searchForMovie(){
	
	//Naar welke id moet er gezocht worden
	var id="movieBox";
	
	//Check of getElementById mag en of er een movieBox is
	if((document.getElementById) && ( document.getElementById(id))){
		var c = document.getElementById( id );
		var m = c.href;
		
		var img = c.getElementsByTagName( "img" );
		img = img[0].src;
		
		placePlayer( c.id , m , img );
	}
}

//Functie, plaatst een flv-player
//placePlayer ::[ id:id van container(wordt  vervangen) , mloc:locatie van media, iloc:locatie van preview-image
//Afhankelijk van swfobject.js
function placePlayer( id , mloc , iloc ){
	
	var flashvars = {
		file: mloc,
		image: iloc
	};
	
	var params = {
		allowfullscreen: "true",
		allowscriptaccess: "always",
		wmode: "opaque"
	};
	
	var attributes = {
		id: "flashPlayer",
		name: "flashPlayer"
	};

	swfobject.embedSWF("/style/swf/player.swf", id , "280", "225", "9.0.0", 0 , flashvars, params, attributes);
}	



/*
############################################
####									####
####	Start Slideshow					####
####	( alleen bij zoeken)			####
####									####
############################################
*/
function startGlider(){
	
	id = "scroller"
	
	if((document.getElementById) && ( document.getElementById(id))){
		
		$("#scroller").scrollable({
		
			size: 1,
			clickable: false,
			loop: false,
			speed: 400
			
			}).circular().navigator({

			navi: "#scrollerNav",
			naviItem: 'a',
			activeClass: 'current'

		}).autoscroll( {
			autoplay: true,
			interval: 9000,
			steps: 1
			
		});		
	}
	
}

/*
############################################
####									####
####	Koppelen inklap zoekfilters		####
####	( alleen bij zoeken)			####
####									####
############################################
*/
function attachFilterEvents(){
	
	if(document.getElementById){
		var io = document.getElementById("io4search");
		
		if( io ){
			var fl = io.getElementsByTagName( "fieldset" );
			
			for( var i=0; i<fl.length; i++ ){
			
				var f = fl[i];
				
				if( f.className == "narrow left" ){
									
					var l = f.getElementsByTagName( "legend" );
					l = l[0];
					
					var span = document.createElement( "span" );
					span.className = "legendspan";
					
					var s = l.innerHTML.replace( " " , "_" );
					var a = document.createElement( "a" );
					a.href = "#open";
					a.id = "a_" + s;
					a.innerHTML = l.innerHTML;
					span.appendChild( a );
					
					insertAfter( f , span );
					
					f.style.display = "none";
					
					/* Mouseevents */
					if(a.addEventListener){
						a.addEventListener( "click" , function(evt)
						{
							if (evt.preventDefault) {
								evt.preventDefault();
								openFieldset( this.id );
						}}, false );
						
						l.addEventListener( "click" , function(evt)
						{
							if (evt.preventDefault) {
								evt.preventDefault();
								openFieldset( this.innerHTML );
						}}, false );
						
					} else {
						a.attachEvent ( "onclick" , function()
						{
							var b = event.srcElement.id;
							openFieldset( b );
							return false;
						} );
						
						l.attachEvent ( "onclick" , function()
						{
							var b = event.srcElement.innerHTML;
							closeFieldset( b );
							return false;
						} );
						
					}
				}
			}
		}
	}
}

function openFieldset( btn ){
	var span = document.getElementById( btn).parentNode;
	span.style.display = "none";
	var io = document.getElementById ( "io4search" );
	var fl = io.getElementsByTagName( "fieldset" );
	for( var i=0; i<fl.length; i++ ){
		var f = fl[i];
		var l = f.getElementsByTagName( "legend" );
		l = l[0];
		ls = "a_" + l.innerHTML.replace( " " , "_" );
		if( ls == btn ){ f.style.display = "block" ; }
	}

}

function closeFieldset( l ){}

function insertAfter( referenceNode, newNode ) { referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling ); }

/*
############################################
####									####
####	Klantentemplate					####
####									####
####									####
############################################
*/

function attachClientView(){
		
	var target = "clientContainer";
	if(( document.getElementById) && ( document.getElementById(target)) ){
		addClientPullout();
	}
}

function addClientPullout(){
				
	$("#clientContainer ul a").bind('click', function(event) {
		event.preventDefault();
		openClient( this );
	});
}

function openClient( t ){
	
	var p = $(t).parent();
	
	var sa = $(p).find( "div" );
	var s ="";
	
	for( var i=0; i<sa.length; i++ ){
		s = s + " " + sa.html();
	}
	
	var ic = $(t).parent().parent().next().next();
	var tekst = s ;
	
	$("#clientContainer li.active" ).removeClass( "active" );
	
	//Close all (and clear all?)
	$("#clientContainer > .info").slideUp( '400' , function(){
		
	});

	
	setTimeout( function(  ){
		$(p).attr( "class" , "active" );
		$(ic).addClass( "active" );
		$(ic).html( tekst );
		$(ic).slideDown( '400' );
	}, 400);

}

function setHeading()
{
	//functie om de eerste h2 te plaatsen in de h1
	if($('h1').text() != $('h2').eq(0).text())
	{
		$('h1').text($('h2').eq(0).text());
		$('h2').eq(0).addClass('nonvisual');
	}
}

function shuffleCloud()
{
	$('#searched ul').shuffle();
}

(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      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;
  }
})(jQuery);
