var szCustomTagSelector = '';

/*********** Functions for snapping blocks to grid canvas ***********/
jQuery.fn.SnapBlocksToGrid = function(szBlockSelector, iThreshold) {
	var iGridPartHeight = 11;
	$(this).each(function(colIdx){
		$(this).find(szBlockSelector).each(function(blockIdx){
			var iHeight = $(this).outerHeight(false);
			if (iHeight > ((Math.floor(iHeight / iGridPartHeight) * iGridPartHeight) + iThreshold)) {
				var iSnappedHeight = ((Math.ceil(iHeight / iGridPartHeight) * iGridPartHeight));
				$(this).css('min-height', iSnappedHeight + 'px');
			}
		});
	});
}


/*********** Functions for loading indicators ***********/
jQuery.fn.Loading = function() { if ($(this).length > 0) { $(this).find('input').attr('disabled', 'disabled'); $(this).append('<div class="loading_panel" style="width:' + $(this).outerWidth() + 'px;height:' + $(this).outerHeight() + 'px;top:' + $(this).position().top + 'px;left:' + $(this).position().left + 'px;"></div>'); } };
jQuery.fn.FinishedLoading = function() { if ($(this).find('.loading_panel').length > 0) { $(this).find('input').attr('disabled', ''); $(this).find('.loading_panel').hide(); } };


/*********** Functions for dimming article blocks ***********/
jQuery.fn.DimBlock = function() { $(this).find('h2').addClass('greyed'); $(this).find('.inner').css('opacity', 0.25); };
jQuery.fn.UnDimBlock = function() { $(this).find('h2').removeClass('greyed'); $(this).find('.inner').css('opacity', ''); };
jQuery.fn.SelectArchetype = function() {
	if (PopupIsActive()) ClosePopups(true);
	var bActive = ($(this).attr('class').indexOf('active') >= 0);
	$('#archetypes ul li a').removeClass('active');
	if (!bActive)
		$(this).addClass('active');
	RefreshCufon();
	DimArticles(2);
}


function DimArticles(iMode) {
	if (iMode != 3)
		szCustomTagSelector = '';
	else if (szCustomTagSelector.length == 0)
		iMode = 2;
	
	if ((iMode == 2) && ($('div.tag_container a.active').length == 0) && ($('#archetypes ul li a.active').length == 0) && ($('a.author_selector.active').length == 0))
		iMode = 1;
	
	if(iMode == 0) { // dim all articles
		$('#grid .block').DimBlock();
	}
	else if (iMode == 1) { // un-dim all articles
		$('#grid .block').UnDimBlock();
	}
	else if (iMode == 2) { // determine to dim which articles
		// loop through all article blocks
		var bAnyArchetypeIsSelected = $('a.archetype_selector.active').length > 0;
		var bAnyTagIsSelected = $('div.tag_container a.active').length > 0;
		var bAnyAuthorIsSelected = $('a.author_selector.active').length > 0;

		$('#grid .block').each(function(blockIdx){
			var bTagSelected = false;
			var bArchetypeSelected = false;
			var bAuthorSelected = false;

			// check CSS classes for article block
			var arrClasses = $(this).attr('class').split(' ');
			for (var i = 0; i < arrClasses.length; i++) {
				var szCssClass = arrClasses[i];
				// check if the css class starts with "archetype_", and a hyperlink element is present AND active
				if ((szCssClass.substr(0, 10) == 'archetype_') && ($('#' + szCssClass + '.active').length > 0))
					bArchetypeSelected = true;
				// check if the css class starts with "tag_", and a checkbox element is present AND checked
				else if ((szCssClass.substr(0, 4) == 'tag_') && ($('div.tag_container a[href=\'#' + szCssClass.substr(4) + '\'].active').length > 0))
					bTagSelected = true;
				else if ((szCssClass.substr(0, 7) == 'author_') && ($('#' + szCssClass + '.active').length > 0))
					bAuthorSelected = true;
			}
			// determine to dim or undim an article block
			// Important: archetype works as XAND operator, and tag works as OR operator!
if (((bAnyArchetypeIsSelected && bArchetypeSelected) || !bAnyArchetypeIsSelected) && ((bAnyTagIsSelected && bTagSelected) || !bAnyTagIsSelected) && ((bAnyAuthorIsSelected && bAuthorSelected) || !bAnyAuthorIsSelected))				$(this).UnDimBlock();
			else
				$(this).DimBlock();
		});
	}
	else if (iMode == 3) { // custom tag
		$('#grid .block').each(function(blockIdx){
			var bDim = true;
			var arrClasses = $(this).attr('class').split(' ');
			for (var i = 0; i < arrClasses.length; i++) {
				var szCssClass = arrClasses[i];
				if (szCssClass == szCustomTagSelector)
					bDim = false;
			}
			if (bDim)
				$(this).DimBlock();
			else
				$(this).UnDimBlock();
		});
	}
	
	// (re)load Cufon, but only for article headings
	RefreshCufon();
}

/*********** Helper functions ***********/
$.GetUrlParameter = function(name) { var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); if (!results) { return ''; } return results[1] || ''; }
function AddToUrl(szUrl, szKey, szValue) { if (szUrl.indexOf('?') >= 0) szUrl += '&'; else szUrl += '?'; szUrl += szKey + '=' + escape(szValue); return szUrl; }


/*********** Article popup functions ***********/
jQuery.fn.AddCloseControl = function() { $(this).append('<a href="Javascript:void(0);" onclick="ClosePopups(true);" class="close_link" alt="Sluiten" title="Sluiten"></a>');  }
function ClosePopups(bDim) {  $('#popup_cover').hide(); $('#popup_article').hide(); $('#popup_greyblock').hide(); if (bDim) { DimArticles(2); }}
function PopupIsActive() { return ($('#popup_article:visible').length > 0) || ($('#popup_greyblock:visible').length > 0); }
function SetPopupCover() {
	$('#popup_cover').show();
	$('#popup_cover').click(function(){ ClosePopups(true); });
}


// RGE: een extra functie, afgekeken van LoadArticle, welke met een argument een artikel laat zien
// Bij voorkeur integreren met LoadArticle. 


ShowHashArticle = function() {
	var hash = location.hash
	var title = 'article-' + hash.substr(1, hash.length)

	var oBlock = $('#' + title);
	var oLink = $(oBlock).find('a.article_link');

	$(oBlock).each(function(){
		ClosePopups(false);
		// dim all articles
		DimArticles(0);
		// show and position article popup
		$('#popup_article').html('');
		$('#popup_article').show();
		$('#popup_article').css({ 'top':oBlock.position().top + 'px', 'left':oBlock.position().left + 'px', 'width':((oBlock.outerWidth() * 2) + 11) + 'px' });
		$('#popup_article').Loading();
		// determine article URL
		var szArticleUrl = oLink.attr('href');

		// RGE: dit gaat niet goed. Op deze manier wordt een pagina id dat in de querystring staat altijd meegegeven
		// Er wordt een correcte url in de link gegenereerd. Dit hoeft niet in js te worden aangepast.
		// Nakijken of dit nergens anders gebeurd.

		//if ((szArticleUrl.indexOf('http://') < 0) && (szArticleUrl.indexOf('https://') < 0))
		//	szArticleUrl = window.location.href + szArticleUrl;
		// load article contents using AJAX
		$.get(AddToUrl(AddToUrl(szArticleUrl, 'ajax', 'yes'), 'dt', new Date().getTime()), function(szHtml) {
			$('#popup_article').FinishedLoading();
			$('#popup_article').html('<div class="inner">' + szHtml + '</div>');
			$('#popup_article').AddCloseControl();
			RefreshCufon();
			// set comments
			//if (szArticleUrl.indexOf('comments=yes') >= 0)
				ShowComments(true);
			//else
			//	HideComments();
			// add-this toolbox links
			$('#popup_article div.addthis_toolbox a').each(function(idx){
				$(this).attr('addthis:url', szArticleUrl);
				$(this).attr('addthis:title', $('#popup_article h2.article_title').text());
			});
			// set focus functions of input fields (initial values disappear)
			$('#popup_article input.field').each(function(){
				var szInitialValue = $(this).attr('value');
				$(this).focusin(function(){ if ($(this).val() == szInitialValue) $(this).val(''); });
				$(this).focusout(function(){ if ($(this).val() == '') $(this).val(szInitialValue); });
			});
			// bind author selector link
			$('a.author_selector').click(function(){ $(this).addClass("active"); $(this).LoadAuthorArticles(); return false; });
			SetPopupCover();
			
			$('.tooltip_container').children("a").click(function() {
				$('.author_selector').removeClass("active");
				$(this).parent().children(".tooltip_user").show(10, function(){
					$('#popup_article, #grid').click(function() {
						$('.tooltip_container').children(".tooltip_user").hide();
					});
				});
			});	
			
			addthis.toolbox(".addthis_toolbox", {}, {title:$('#popup_article h2.article_title').text(), url:szArticleUrl});
		});

	});
	
}


ShowDirectArticle = function(szArticleUrl) {
    	
	// find the block where the popup should be opened
	
	//reg = new RegExp(/(?:p=)(.*)/); 
	//arr = reg.exec(szArticleUrl); 
	//if (arr) if ( arr[1]){
	//	var oBlock = $('#article-' + arr[1]);
	//}

	var title = 'article-' + szArticleUrl.substr(30, szArticleUrl.length - 31)
	var oBlock = $('#' + title);
    	
	$(oBlock).each(function() {
	
		ClosePopups(false);
		// dim all articles
		DimArticles(0);
	    
		// scrollto the block position
		
		// show and position article popup
		$('#popup_article').show();

		$('#popup_article').css({ 'top':$(this).position().top + 'px', 'left':$(this).position().left + 'px', 'width':(($(this).outerWidth() * 2) + 11) + 'px' });
    	
		// scrollto
		$(window).scrollTop($('#' + title).offset().top - $('#archetypes').offset().top - $('#archetypes').outerHeight());

		$('#popup_article').AddCloseControl();
		RefreshCufon();
		
		// set comments
		if (szArticleUrl.indexOf('comments=yes') >= 0)
		    ShowComments(true);
		else
		    HideComments();
		
		// add-this toolbox links
		$('#popup_article div.addthis_toolbox a').each(function(idx){
		    $(this).attr('addthis:url', szArticleUrl);
		    $(this).attr('addthis:title', $('#popup_article h2.article_title').text());
		});

		// set focus functions of input fields (initial values disappear)
		$('#popup_article input.field').each(function(){
		    var szInitialValue = $(this).attr('value');
		    $(this).focusin(function(){ if ($(this).val() == szInitialValue) $(this).val(''); });
		    $(this).focusout(function(){ if ($(this).val() == '') $(this).val(szInitialValue); });
		});

		// bind author selector link
		$('a.author_selector').click(function(){ $(this).LoadAuthorArticles(); return false; });
		SetPopupCover();
		
		addthis.toolbox(".addthis_toolbox", {}, {title:$('#popup_article h2.article_title').text(), url:szArticleUrl});
		
	});
	
}

jQuery.fn.LoadArticle = function() {
	var oBlock = $(this);
	var oLink = $(this).find('a.article_link');
	if (($(this).attr('href') != null) && ($(this).attr('href').length > 0)) {
		oBlock = $(this).parent().parent();
		oLink = $(this);
	}
	ClosePopups(false);
	// dim all articles
	DimArticles(0);
	// show and position article popup
	$('#popup_article').html('');
	$('#popup_article').show();
	$('#popup_article').css({ 'top':oBlock.position().top + 'px', 'left':oBlock.position().left + 'px', 'width':((oBlock.outerWidth() * 2) + 11) + 'px' });
	$('#popup_article').Loading();
	// determine article URL

	var szArticleUrl = oLink.attr('href');


	var id = $(oBlock).attr('id');
	location.hash = id.replace('article-','#')
	

	// RGE: dit gaat niet goed. Op deze manier wordt een pagina id dat in de querystring staat altijd meegegeven
	// Er wordt een correcte url in de link gegenereerd. Dit hoeft niet in js te worden aangepast.
	// Nakijken of dit nergens anders gebeurd.

	//if ((szArticleUrl.indexOf('http://') < 0) && (szArticleUrl.indexOf('https://') < 0))
	//	szArticleUrl = window.location.href + szArticleUrl;
	// load article contents using AJAX
	$.get(AddToUrl(AddToUrl(szArticleUrl, 'ajax', 'yes'), 'dt', new Date().getTime()), function(szHtml) {
		$('#popup_article').FinishedLoading();
		$('#popup_article').html('<div class="inner">' + szHtml + '</div>');
		$('#popup_article').AddCloseControl();
		RefreshCufon();
		// set comments
		//if (szArticleUrl.indexOf('comments=yes') >= 0)
			ShowComments(true);
		//else
		//	HideComments();
		// add-this toolbox links
		$('#popup_article div.addthis_toolbox a').each(function(idx){
			$(this).attr('addthis:url', szArticleUrl);
			$(this).attr('addthis:title', $('#popup_article h2.article_title').text());
		});
		// set focus functions of input fields (initial values disappear)
		$('#popup_article input.field').each(function(){
			var szInitialValue = $(this).attr('value');
			$(this).focusin(function(){ if ($(this).val() == szInitialValue) $(this).val(''); });
			$(this).focusout(function(){ if ($(this).val() == '') $(this).val(szInitialValue); });
		});
		// bind author selector link
		$('a.author_selector').click(function(){ $(this).addClass("active"); $(this).LoadAuthorArticles(); return false; });
		SetPopupCover();
		
		$('.tooltip_container').children("a").click(function() {
			$('.author_selector').removeClass("active");
		 	$(this).parent().children(".tooltip_user").show(10, function(){
				$('#popup_article, #grid').click(function() {
					$('.tooltip_container').children(".tooltip_user").hide();
				});
			});
		});	
		
		addthis.toolbox(".addthis_toolbox", {}, {title:$('#popup_article h2.article_title').text(), url:szArticleUrl});
	});
	
}
jQuery.fn.LoadAuthorArticles = function() {
	
	ClosePopups(false);
	//if (szCustomTagSelector.length > 0) {
	//	szCustomTagSelector = '';
		DimArticles(2);
	//}
	//else {
	//	szCustomTagSelector = $(this).attr('href');
	//	DimArticles(3);
	//}
	return false;
}
jQuery.fn.LoadGreyBlock = function() {
	ClosePopups(false);
	// dim all articles
	DimArticles(0);
	// show and position article popup
	$('#popup_greyblock').html('');
	$('#popup_greyblock').show();
	$('#popup_greyblock').css('top', $(window).scrollTop() + $('#grid').position().top);
	$('#popup_greyblock').Loading();
	// determine article URL
	var szArticleUrl = $(this).attr('href');
	szArticleUrl = AddToUrl(szArticleUrl, 'ajax', 'yes');
	szArticleUrl = AddToUrl(szArticleUrl, 'dt', new Date().getTime()); // anti-cache
	// load article contents using AJAX
	$.get(szArticleUrl, function(szHtml) {
		$('#popup_greyblock').FinishedLoading();
		$('#popup_greyblock').html('<div class="inner">' + szHtml + '</div>');
		$('#popup_greyblock').AddCloseControl();
		$('#popup_greyblock a.greyblock_link').click(function(){ $(window).scrollTop(0); $(this).LoadGreyBlock(); return false; });
		SetPopupCover();
		RefreshCufon();
		// bind author selector link
		$('a.author_selector').click(function(){ $(this).addClass("active"); $(this).LoadAuthorArticles(); return false; });
		
	});
	
	RefreshCufon();
};

function ShowComments(bScrollTo) {
	$('#comments_link').hide();
	$('#comments_container').show();
}
function HideComments() {
	$('#comments_link').show();
	$('#comments_container').hide();
}

/*********** Cufon functions ***********/
function LoadCufon() {
	// load cufon
	var arrClasses = new Array('h1','#archetypes h2', '#left_column h2','#popup_greyblock h2', 'h3','#archetypes ul li a');
	Cufon.set('fontFamily', 'Storno');
	jQuery.each(arrClasses, function(idx){ Cufon.replace(arrClasses[idx]); });
	
	// In IE6 and IE7, Cufon hyperlinks do not render hyperlink areas properly.
	// We create clickable div's over them to mimick proper hyperlink behaviour.
	if ($.browser.msie && ($.browser.version <= 7)) {
		jQuery.each(arrClasses, function(idx){ 
			var szClass = arrClasses[idx];
			$(szClass).each(function(elIdx){
				var oEl = $(szClass).eq(elIdx);
				if ((oEl.attr('href') != null) && (oEl.attr('href').length > 0)) {
					var oCover = oEl.append('<div></div>');
					oCover.css({'width':'100%', 'height':'100%'});
				}
				else if ($(szClass).eq(elIdx).find('a').length > 0) {
					$(szClass).eq(elIdx).find('a').each(function(subelIdx){
						var oSubEl = $(szClass).eq(elIdx).find('a').eq(subelIdx);
						var oCover = oSubEl.append('<a></a>');
						oCover.attr('href', oSubEl.attr('href'));
						oCover.css({'display':'block', 'width':'100%', 'height':'100%'});
					});
				}
			});
		});
	}
}
function RefreshCufon() {
	Cufon.refresh();
}



/*********** Page load ***********/
$(document).ready(function() {
	// Load Cufon first, to minimize "flicker" of headings
	LoadCufon();
	
	// resize images in blocks
	$('#grid .block img').each(function(){
		var dRatio = ($(this).height() / $(this).width());
		var iImageWidth = 202;
		var iImageHeight = iImageWidth * dRatio;
		$(this).width(iImageWidth);
		$(this).height(iImageHeight);
	});
	
	
	$(window).hashchange( function(){
		ShowHashArticle()
	});	


	$(window).hashchange();


	// manually manipulate total grid width to force horizontal scroll if needed
	$('#grid').css('width', $('#grid .column').length * $('#grid .column').eq(0).outerWidth(true));
	
	// snap left column and article blocks to grid canvas
	$('#grid .column').SnapBlocksToGrid('div.block', 0);
	$('#left_column').SnapBlocksToGrid('div.block', 0);
	
	// set hyperlink click to grey blocks
	$('#left_column div.grey div.inner').click(function(){
		if(!$(this).find('a').eq(0).hasClass('tag_selector'))
			$(this).find('a').eq(0).click();
	});
	
	// set block hover CSS (cannot use regular :hover selector due to browser issues
	$('#grid .block').mouseenter(function(){ if (!PopupIsActive()) $(this).addClass('mouseover'); });
	$('#grid .block').mouseleave(function(){ $(this).removeClass('mouseover'); });
	
	$('.block.green.green_hover').mouseenter(function(){ $(this).addClass('mouseover'); RefreshCufon(); });
	$('.block.green.green_hover').mouseleave(function(){ $(this).removeClass('mouseover'); RefreshCufon(); });

	// RPG: dit moet anders kunnen: er was een algemene methode voor...

	$('#tags').find('h2').toggle(function(){$(this).parent().parent().find('.tag_container').show();}, function(){$(this).parent().parent().find('.tag_container').hide();});
	
	// toggle content expanders
	$('.togglecontent_link').toggle(function(){$(this).parents(".block.grey").addClass('active'); $('.togglecontent').hide();},function(){$(this).parents(".block.grey").removeClass('active');$('.togglecontent').show();});
	//$('a.togglecontent_link').click(function() { $('#'+jQuery.trim($(this).attr('class').replace('togglecontent_link', ''))).toggle(); return false; });
	
	// click on block loads the article popup
	$('a.article_link_comments').click(function(){ $(this).LoadArticle(); return false; });
	$('a.author_selector').click(function(){ $(this).LoadAuthorArticles(); return false; });
	$('#grid .block').click(function(){ $(this).LoadArticle(); return false; });
	$('a.greyblock_link').click(function(){ $(this).LoadGreyBlock(); return false; });
	
	// archetype and checkbox selectors which dim/undim articles
	$('a.archetype_selector').click(function(){ $(this).SelectArchetype(); $(this).addClass('active_hover'); RefreshCufon(); return false; });
	$('div.tag_container a.tag_selector').click(function(){ 
		if (PopupIsActive())
			ClosePopups(false); 
		if ($(this).hasClass('active'))
			$(this).removeClass('active');
		else
			$(this).addClass('active');
		DimArticles(2); 
	});
	// force archetype hover states
	$('#archetypes ul li a').mouseenter(function(){ if($(this).attr('class').indexOf('active') >= 0) { $(this).addClass('active_hover'); RefreshCufon(); } });
	$('#archetypes ul li a').mouseleave(function(){ $(this).removeClass('active_hover'); RefreshCufon(); });

	$('#archetypes ul li a').mouseenter(function(){ $(this).addClass('hover'); RefreshCufon();  });
	$('#archetypes ul li a').mouseleave(function(){ $(this).removeClass('hover'); RefreshCufon(); });	

	// load an article, if an "articleid" was specified as URL parameter
	var szArticleID = $.GetUrlParameter('articleid');
	if((szArticleID.length > 0) && ($('#' + szArticleID).length > 0))
		$('#' + szArticleID).LoadArticle();
		
	$('a.author_selector').toggle(function(){  $(this).addClass("active"); $(this).LoadAuthorArticles(); return false; },function() { $(".author_selector").removeClass("active"); DimArticles(1); });
	

});


