/*
	graphical user interface scripts
*/
var $j;	

	jQuery.noConflict();
	$j = jQuery;

window.onload=function(){
	if (document.getElementsByClassName == undefined) {
		document.getElementsByClassName = function(className)
		{
			var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
			var allElements = document.getElementsByTagName("*");
			var results = [];

			var element;
			for (var i = 0; (element = allElements[i]) != null; i++) {
				var elementClass = element.className;
				if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
					results.push(element);
			}
			return results;
		}
	}
	
	
	
	initFancyBox();
	if( typeof(window.makeEditable ) == 'function') 
		makeEditable();
	
	/*addLinkIcons();*/
	add_events_links();
	prepare_menu();
	add_click_searchbox();
	fixMainMenu();
	add_toelichtingen();
	startGlider();
	
	if(typeof(onloadBekendmakingen) == 'function')	
		onloadBekendmakingen();	
	if(typeof(onloadAdressen) == 'function')	
		onloadAdressen();	
	if(typeof(onloadRegelingen) == 'function')	
		onloadRegelingen();	
	
}

function startGlider(){
	$j('ul.items').innerfade({
		speed: 2000,
		timeout: 7000,
		type: 'sequence',
		containerheight: '188px'
	});
}


function fixMainMenu(){
	
	//Init	
	var noc = 3; // Number of columns
	
	$j("#menu .level1").each( function( key, top )
	{

		// Find total number of elements in submenu
		var c = 0; // counter for total
		var p = 0; // counter for first-level items
		$j(top).find( ".level2").each( function ( id , second )
		{
			c = c + $j(second).find(".level3").length + 1;
			p = p + 1;
			
		});
		
		// If total is larger than the amount of columns, then run this script
		if( c >= noc )
		{
			/* Calculate average */
			var avr = Math.ceil(c / noc)+1;
			
			// Set startingpositions
			var pos = 1; // Var for position of koloms
			var cur = 1; // Var for position in total flow
			
			// Create first column
			$j(top).find("ul").slice(0,1).prepend ( "<li><ul class='kolom k"+pos+"'/></li>" );
			
			// Reposition all li's with link
			$j(top).find("ul:not(.kolom) li a").each( function ( nr , link ){
				
				if( cur <= avr ) {
					
					if(( cur == avr ) && ($j(link).parent().hasClass("level2")) ){
						cur = 1;
						pos = pos + 1;
						$j(top).find("ul").slice(0,1).find("li").slice(0,1).append ( "<ul class='kolom k"+pos+"'/>" );
					}
					
					$j(top).find( '.k' + pos).append($j(link).parent() );
					cur = cur + 1;
					
					
				} else {
					cur = 1;
					pos = pos + 1;
					$j(top).find("ul").slice(0,1).find("li").slice(0,1).append ( "<ul class='kolom k"+pos+"'/>" );
					$j(top).find( '.k' + pos).append($j(link).parent() );
				}
			});
			
			$j(top).find("li").slice(0,1).addClass("kc");
		}
	});
	
	
	/* Remove empty ul */
	$j("#menu ul").each( function ( n , u ){
		var elem = $j(this);
		if (elem.children().length == 0) {
		  elem.remove();
		}

	});
}

function initFancyBox()
{
	$j("a.gallery").each(function(key, value)
	{
		$j(value).attr('rel','aap');
	});
	
	$j("a.gallery").fancybox({
		'type'	: 'image',
		'titleShow' : true,
		'transitionIn' : 'fade',
		'transitionOut' : 'fade'
	});
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}




/* formulieren */
function add_toelichtingen()
{
	var labels = document.getElementsByTagName('label');
	for (var n = 0; n < labels.length; n++)
	{
		var labl = labels[n];
		var ltitle = labl.getAttribute('title');
		if (ltitle)
		{
			var attr = labl.getAttribute('for');
			if (!attr)
			{
				// older IE's are evil
				attr = labl.attributes["for"].value
			}
		
			var inp = document.getElementById(attr);
			if (inp)
			{
				inp.onfocus = function () { show_toelichting(this) }
				inp.onblur  = function () { hide_toelichting(this) }
			}		
		}
	}
}

function show_toelichting (a_input)
{
	msg = document.createTextNode(a_input.getAttribute('title'));
	
	msgp = document.createElement('p');
	msgp.setAttribute('id','toelichting_' + a_input.getAttribute('id'));
	msgp.className = 'toelichting';

	img = document.createElement('img');
	img.setAttribute('src','/style/images/balloon.png');
	img.setAttribute('alt','toelichting');
	img.setAttribute('id','balloon');

	msgp.appendChild(img);
	msgp.appendChild(msg);
	
	
	var pos = findpos(a_input);
	var correction = 12
	
	msgp.style.top = (pos[1] - correction) + 'px';
	
	msgp.style.left = '375px';
	if (a_input.nodeName == 'TEXTAREA')
	{
		msgp.style.left = '480px';
	}
	
	var sb = document.getElementById('content');
	sb.appendChild(msgp);
}

function hide_toelichting (a_input)
{
	var sb  = document.getElementById('content');
	var del = document.getElementById('toelichting_' + a_input.getAttribute('id'));
	if (del)
	{ 
		sb.removeChild(del);
	}
}

function findpos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		do 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} 
		while (obj = obj.offsetParent);
	
		return [curleft,curtop];
	}
}





/*
 * Seach form functions
*/

function add_click_searchbox()
{
	set_click('q');
	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 == 'Vul hier uw zoekopdracht in')
	{
		a_box.value = '';
	}
	if (a_box.value == 'Uw zoekopdracht')
	{
		a_box.value = '';
	}
}






/*
 * 
*/
function add_anchor_events()
{
	var content = document.getElementById('content');
	var links = content.getElementsByTagName('a');
	for (var n = 0; n < links.length; n++)
	{
		var l = new String(links[n].getAttribute('href'));
		if (l.indexOf('#') > -1)
		{
			links[n].onclick = function(){backlight(this)}
		}
	}
}

function toggleEditForm()
{
	toggle = document.getElementById('social_networks');
	toggle2 = document.getElementById('display');
	if (hasClass(toggle, "hidden"))
	{
		removeClass(toggle, "hidden");
		addClass(toggle2, "hidden");
	}
	else
	{
		removeClass(toggle2, "hidden");
		addClass(toggle, "hidden");
	}
}

function newwin()
{
	window.open(this.href,'_blank');
	return false;
}

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++)
	{
		title	= links[i].getAttribute('title');
		if(title == null)
			title = links[i].getAttribute('href');		
		
		var classes = links[i].className.split(' ');
		for(var j = 0; j < classes.length; j++)
		{
			switch (classes[j])
			{
				case 'newwindow':
					links[i].setAttribute('title', title + ', opent in een nieuw venster.');  
					links[i].onclick = newwin;
					links[i].innerHTML = links[i].innerHTML + img;
					break;
				case 'newwindownoicon':
					links[i].setAttribute('title', title + ', opent in een nieuw venster.');  
					links[i].onclick = newwin;
					links[i].innerHTML = links[i].innerHTML;
					break;	
			}
		}
	}
}


/*
 * login form functions
*/
function hide_login()
{
	$j('#login').offset({top: -45});

	$j('#togglelogin').toggle(
	
		function()
		{
			$j('#login').animate({"top": "+=43px"}, "600");
			$j("#login input[name='username']").focus();
		},
		function()
		{
			$j('#login').animate({"top": "-=43px"}, "fast");
		}
	);
};



/* ----- ---- - --- -- -- - ----- -- --- - ---- - -*/

function prepare_menu()
{
	var menu = document.getElementById('submenu');
	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') != 'submenu')
			{
				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('onclick','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)
						};
		}
	}
}

