/**
 * Attach the modalbox upon event (click)
 * 
 * @param evt
 * @return void
 */
function attach_modal_box(evt) {
	evt.preventDefault();
	open_modal_box($(this).attr('href'));
}

/**
 * Open a modalbox with a certain url
 * 
 * @param href
 * @return
 */
function open_modal_box(href) {
	// Create modalbox
	var modal_active = false;
	if ($('#modalContainer').length == 0) {
		$('#modal_wrapper').modal({
			closeClass: 'modal-close',
			overlay: 75,
			onClose: modalClose,
			onShow: modalShow
		});
		
	} else {
		var modal_active = true;
	}
	
	// Add loader progress
	$('#modal_content').append('<div class="loading"></div>');
	// Load content using AJAX
	$.get(href, {type:10}, function(data, textStatus) {
		$('#modal_content').html(data);
		$('a[href^="http://"]', $('#modal_content')).attr('rel', 'external').attr('target', '_blank');
		$('#modal_content .loading').remove();
		$('#modalContainer #modal_wrapper').removeClass('hidden');
		if (!modal_active) {
			$('#modalOverlay').click()
		}
		Cufon.refresh();
	}, 'html');
	// Google pageTracker for AJAX requests
	if (window.pageTracker != undefined) {
		window.pageTracker._trackPageview(href);
	}
}

/**
 * Modalbox (lightbox overlay)
 * 
 * @return void
 */
function modalbox() {
	// Inject invisible modalbox into body element
	$('body').prepend('<div id="modal_wrapper" class="hidden"><div id="modal_top"></div><div id="modal_content"></div><div id="modal_bottom"></div></div>');
	$('a').filter(function() {
		return (this.href.match('/.*noorderslag\/panel.*') || this.href.match('.+/noorderslag\/act\/.+')) && !($(this).parent().parent().hasClass('pageBrowser'));
	}).attr('rel', 'lightbox');
	$('a[class="popup"],a[class="lightbox"],a[rel="lightbox"]').click(attach_modal_box);
}

/**
 *  Capture keydown events
 *  
 * @param evt Event object
 * @return void
 */
function modalKeyDown(evt) {
	if (evt.keyCode == 27) {
		$.modal.close();
	}
}

/**
 * Callback function when dialog is displayed
 * 
 * @param dialog
 * @return void
 */
function modalShow(dialog) {
	// Make scrolling possible (removed fixed position)
	dialog.container.css('position', 'absolute');
	var max_scroll_top = Math.max($('body').attr('scrollTop'), $('html').attr('scrollTop'));
	dialog.container.css('top', (max_scroll_top + 20)+'px');
	// Disable Flash elements (problems with z-index)
	$('#picture_container,#footer_radio_tv').hide();
	$(window).bind('keydown', modalKeyDown);
	// Click outside should close modalbox (event gets fired twice?)
	$(dialog.overlay).bind('click', function() {
		if ($(this).attr('clicked'))
			modalClose()
		else
			$(this).attr('clicked', true);
	});
	$('body').addClass('modal-active');
}

/**
 * Modalbox close event
 * 
 * @param dialog
 * @return void
 */
function modalClose(dialog) {
	$('#picture_container,#footer_radio_tv').show();
	$.modal.close();
	$(window).unbind('keydown', modalKeyDown);
	$('body').removeClass('modal-active');
}


$(document).ready(function() {
		
	/* Radio & TV carousel */
	if ($('#footer_radio_tv')) {
		var L = ($('body').hasClass('lang_en')) ? 1 : 0; 
		var flashvars = {fvConfigXmlUrl:"/index.php?type=802%26id=6%26L="+L, fvCacheConfig:"true"};
		var params = {wmode:"transparent"};
		var attributes = {};
		swfobject.embedSWF(	
			"/fileadmin/templates/flash/tvcarousel.swf?r=$Rev: 58593 $", 
			"footer_radio_tv", 
			"100%", 
			"100%", 
			"9.0.115.0",
			"/fileadmin/templates/flash/expressInstall.swf",
			flashvars,
			params,
			attributes);
	}
	
	/** deelnemers **/
	var btnObj = $('#logoutbtn');
	var link = $('<a href="#" class="logout">' + btnObj.attr('value') + '</a>');
	link.click(function(){
		btnObj.click();
	});
	btnObj.hide().after(link);
	
	$('.help').click(function(){
		$('.help-content').show().bind('click', function(){
			$(this).hide().unbind('click');			
		});
	});
	
	// automatische legen van velden
	$('#tt_address_form input#tt_address_name').infoFill();	
	$('#tt_address_form input#tt_address_email').infoFill();	
	$('#searchform .searchbox').infoFill();
	
	if ($('#home-highlight')) {
		
		if ($('body').hasClass('p6')){
			if ($('body').hasClass('lang_en')){
				var flashvars = {fvConfigXmlUrl:"/index.php?type=803%26id=6%26L=1%26no_cache=1", fvCacheConfig:"true"};
			} else {
				var flashvars = {fvConfigXmlUrl:"/index.php?type=803%26id=6%26L=0%26no_cache=1", fvCacheConfig:"true"};
			} 
		}else if($('body').hasClass('p8')){
			if ($('body').hasClass('lang_en')){
				var flashvars = {fvConfigXmlUrl:"/index.php?type=803%26id=8%26L=1%26no_cache=1", fvCacheConfig:"true"};
			} else {
				var flashvars = {fvConfigXmlUrl:"/index.php?type=803%26id=8%26L=0%26no_cache=1", fvCacheConfig:"true"};
			}				
		}
		
		var params = {wmode:"transparent"};
		var attributes = {};
		swfobject.embedSWF(
			"/fileadmin/templates/flash/highlight.swf", 
			"home-highlight", 
			"100%", 
			"100%", 
			"9.0.115.0",
			"/fileadmin/templates/flash/expressInstall.swf",
			flashvars,
			params,
			attributes);
	}
	
	$('#submitnewsletter').bind('click', function(evt) {
		evt.preventDefault();
		$('#newslettercontainer form').submit();
	});
	
	/* Language Hover */
	$('#lang-0, #lang-1, #home_festival, #home_conference').addHover();
	
	/* Random background */
	$('body').randomClass('back_1', ['back_1', 'back_2', 'back_3']);
	
	/* Modalbox */
	modalbox(); 
	
	
	//if ($.fn.filestyle){
	//	$("input[type=file]").filestyle({ 
	//	     image: "/fileadmin/templates/images/buttons/browse.png",
	//	     imageheight : 23,
	//	     imagewidth : 81
	//	 });
	//}
	
});


$.fn.infoFill = function() {
	var label = $(this).attr('value');
	$(this).bind('focus', function() {		
		if ($(this).attr('value') == label){
			$(this).attr('value','');
		}
	}).bind('blur', function() {
		if ($(this).attr('value') == '') {
			$(this).attr('value', label);
		}		
	});
}


$.fn.randomClass = function(replaceClass, classList) {	
	var rand = Math.floor(Math.random() * classList.length);	
	$(this).removeClass(replaceClass).addClass(classList[rand]);
}

$.fn.addHover = function() {
	$(this).hover(
		function() {
			$(this).addClass('hover');
		}, 
		function(){
			$(this).removeClass('hover');
		}
	);
};

/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0) 
				times = 0;
			
			times = times || 0;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});