$(function() {	
	//$("#zoeken input[name=q]").defaultText(vertaling.searchText);
	
	$("#breadcrumbs").prependTo("#main");
	$("h1").addClass("fixed").removeClass("fixed");
	
	$('<a id="print_page"><img src="images/icon_print.png" alt="Print deze pagina"/></a>').click(function(e) {
		e.preventDefault();
		window.print();
		return false;
	}).prependTo("#languages");
	
//	$("#nieuws li, .block:has(a.more)").click(function(e) {
//		if (!$(e.target).is("a")) {
//			$("a", this).each(function() { window.location =  this.href; });
//		}
//	}).hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); });
	
	function slideNewsToNext() {
		newsTimeout = null;
		
		var next = cur.next();
		if (next.length == 0)
			next = cur.siblings(":first");
		slideNewsTo(null, next);
	}
	
	var newsTimeout = null;
	var newsSlideDuration = 5000;
	function scheduleSlideNews() {
		if (newsTimeout)
			clearTimeout(newsTimeout);
		newsTimeout = setTimeout(slideNewsToNext, newsSlideDuration);
	}
	
	function slideNewsTo(e, obj) {
		if (obj == undefined)
			obj = $(this).closest("li");
		
		if (cur.length && obj.get(0) == cur.get(0))
			return;
		cur.find(".content").slideUp();
//		cur.animate({ backgroundColor: color }, 1000);
		cur.find("h2").animate({color: '#ffffff', backgroundColor: color });
		
		cur = obj;
		cur.find(".content").slideDown();
//		cur.animate({ backgroundColor: '#ffffff' }, 1000);
		cur.find("h2").animate({color: color, backgroundColor: '#ffffff' }, scheduleSlideNews);
		
	}
	var color = $("#nieuws h2").css("backgroundColor");
	
//	$("#nieuws h2").css("backgroundColor", "#ffffff");
	var cur = $("#nieuws li:eq(0)");
	$("#nieuws li").each(function() {
		$(">*:gt(0)", this).wrapAll($("<div></div>").addClass('content'));
	}).find("h2").click(slideNewsTo).css("cursor", "pointer");
	$("#nieuws li:first h2").css({ backgroundColor: '#ffffff', color: color });
	$("#nieuws li:gt(0) .content").hide();
	
	$("#nieuws").show();
	if ($("#nieuws li").length > 1)
		scheduleSlideNews();
	
	function hexColor(color) {
		rgb = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
		function hex(x) {
			return ("0" + parseInt(x).toString(16)).slice(-2);
		}
		if (rgb)
			return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
		else
			return color;
    }
    
    var tempActive = $("#tagcloud a:first").addClass("active");
	var activeColor = tempActive.css("color");
	tempActive.removeClass("active");

	function setupJSCloud() {
		tcp = $("#tagcloud");
		
		tcl = tcp.offset().left;
		tcw = tcp.width();
		
	//	tcp.removeAttr('id');
	//	
	//	tcp.wrap($('<div id="tagcloud"></div>').css({overflow: 'hidden'})).css({left: 0/*'-150px'*/, top: 0, width: '10000px' });
	//	
	//	$("#tagcloud ul").attr("class", "row1");
		
		var inactiveColor = $("#tagcloud a").css("color");
		
		jQuery.fn.removeColor = function (animate) {
			var a = this.children().removeClass("active");
			if (animate == undefined || animate) {
				a.animate({color: inactiveColor}, function() { 
					$(this).attr("style", ""); 
					//console.log(this, $(this).attr("style"));
					});
			}
			return this;
		}
		
		jQuery.fn.addColor = function(animate, done) {
			var a = this.children().addClass("active");
			if (animate == undefined || animate) {
				a.css("color", inactiveColor)
					.delay(200).animate({color: activeColor}, 800, function() { 
						$(this).attr("style", "");
						if (done)
							done();
						});
			}
			return this;
		}
		
		var lastTime = $.now();
	
		function setupTagRow(index, relocate) {
			var animMiddle = index == 4;
			var curIndex = index;
			
			$("#tagcloud .row"+index).css( {marginLeft: "0px", clear: 'left'});
			//var offsetTop = $("#tagcloud .row"+index).offset().top;
			
			var foundIndex = -1;
			var selected = false;
			$("#tagcloud .row" + index + " li").each(function(i) {
				if (animMiddle && !selected && (($(this).offset().left + $(this).width()) - tcl > tcw / 2)) {
					selected = true;
					$("a", this).addClass("active");
				}
				
				if ($(this).offset().left > tcl + tcw) {
					foundIndex = i;
					return false;
				}
			});
	//		
	//		if (relocate)
	//			$("#tagcloud").append($('<ul class="row' + (index + 1) + '"></ul>').append($("#tagcloud .row" + index + " li:gt(" + (foundIndex-1) + ")")));
			
			//TODO: zet active meteen goed adhv margin die straks gezet gaat worden
			var row = $("#tagcloud .row" + index);
			var last = row.find(">*:last");
			var width = last.offset().left + last.outerWidth(true) - row.offset().left;
			row.append(row.children().clone());
			jQuery.fx2 = function(elem, obj, x) {
				this.elem = elem;
			};
			
			jQuery.fx2.prototype = {
				custom: function(from, to, unit) {
					var t=this;
					t.end = to;
					setInterval(function() {
						t.now = new Date().getTime();
						t.update();
					}, 13);
				}
			};
			
			var anim = new jQuery.fx(row, {duration: Infinity}, null);
			var speed = ((4 - index) / 4 + 1) * 738/50000;
			
			var leftElem = row.children().eq(1);
			var rightElem = row.children().eq(foundIndex);
			//console.log(leftElem, rightElem);
			//return;
			var lastVal = Infinity;
			var first = true;
			anim.update = function() {
				var val = anim.now * speed % anim.end;
				
				anim.elem.css("marginLeft", -val + "px");
				if (animMiddle) {
					var act = anim.elem.find(":has(.active)");
									
	//				first = false;
					
					if (val < lastVal) {
						act.children().removeClass("active").parent().parent().children().each(function() {
							var t = $(this);
							if (t.position().left + t.width() > tcw / 2) {
								t.find("a").addClass("active");
								return false;
							}
						});
					} else if (act.position().left + act.width() < tcw / 2) {
						act.removeColor().next().addColor();
					}
				} else {
	//				if (first) {
	//					first = false;
	//					
	//					console.log(leftElem.index(), rightElem.index());
	//					setRandomElem();
	//					
	//				}
					
	//				if (anim.now - lastTime > 6000) {
	//					setRandomElem();
	//					lastTime = anim.now;
	//				}
					
					if (val < lastVal) {
						// % is weer afgerond
						var lis = anim.elem.children();
						if (!first && curElem.index() >= lis.length / 2) {
							curElem.removeColor(false);//dont animate
							curElem = lis.eq(curElem.index() - lis.length / 2);
							curElem.addColor(false);//dont animate;
						}
						
						leftElem = rightElem = null;
						lis.each(function() {
							var left = $(this).position().left;
							if (leftElem == null && left > 0) {
								leftElem = $(this);
							}
							
							if (left > tcw) {
								rightElem = $(this);
								return false;
							}
						});
	//					if (rightElem == null)
	//						rightElem = anim.elem.children().last();
					}
					
					while (leftElem.position().left < 0)
						leftElem = leftElem.next();
					while (rightElem && rightElem.position().left < tcw) {
						rightElem = rightElem.next();
						if (rightElem.length == 0) {
							rightElem = null;
						}
					}
				}
				
				lastVal = val;
			};
			
			var curElem = row.find("li:has(.active)");
			
			function doReschedule() {
				var step = 2000;
				var delay = Math.max(lastTime + step - $.now(), 0);
				setTimeout(setRandomElem, delay);
				lastTime = $.now() + delay;
	//			lastTime = $.now() - 1000 + delay;
			}
			
			function setRandomElem() {
				curElem.removeColor();
				var lis = anim.elem.children();
				var min = leftElem.index();
				var max = rightElem == null ? lis.length - 1 : rightElem.index() - 1;
				var cur = curElem.index();
				var val = Math.randomExclude(min, max, cur);
				curElem = lis.eq(val);
					//console.log('next', anim.elem.index(), val, curElem, reschedule);
				
				var done = !first ? doReschedule : undefined;
				curElem.addColor(!first, done);//.children().addClass("active");
			}
			
			anim.custom(0, width, null);
			
			if (!animMiddle) {
				//console.log('range', leftElem.index(), rightElem.index());
				setRandomElem();
	
				doReschedule();
	//			setTimeout(function() {
	//					//console.log('intervalling');
	//					setRandomElem();
	//					//setInterval(setRandomElem, 6000);
	//				}, index * 2000);
	//			lastTime = $.now() + index * 2000;
			}
			
			first = false;
	
			//console.log(width);
		}
		
		setupTagRow(1, true);
		setupTagRow(2, true);
		setupTagRow(3, true);
		setupTagRow(4, false);
	}
	
	function setupFlashCloud() {
		var lines = JSON.stringify($("#tagcloud>ul").map(function() {
			return [$("a", this).map(function() {
				return {href: this.href, text: $(this).text()};
			}).toArray()];
		}).toArray());
		//lines = {};
		$("#tagcloud").flash({hasVersion: 8, hasVersionFail: function() { setupJSCloud(); return false; }, swf: "flash/cloud.swf", width: 738, height: 130, flashvars: {lines: lines, color: hexColor(activeColor).substr(1)}});
	}
	
	setupFlashCloud();
	
//	var count = 0;
//	setInterval(function() {
//		console.log('interval', count++);
//	}, 1000);
	
	//$("#tagcloud").animate({ left: 0}, 10000);
	
	//$("#tagcloud .row4:eq(0)").css( {marginLeft: "-20px", clear: 'left'});
	
	//$("#footer li:last a").fancybox({href: "config.php", type:'iframe', width: 300, height: 200});
});

Math.randomExclude = function(min, max, exclude) {
	var adjust = min <= exclude && exclude <= max ? 0 : 1;
	
	var val = Math.floor(Math.random() * (max - min + adjust)) + min;
	
	if (exclude >= min && val >= exclude)
		val += 1;
	
	return val;
}

$("html").addClass("js");

