
// js p. ************************************************************************************************


/*
http://yelotofu.com/2008/08/jquery-shuffle-plugin/
*/
	(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);

/*
domWindow
*/

(function($){
	
	//closeDOMWindow
	$.fn.closeDOMWindow = function(settings){
		
		$('#holyDomWindowContent').html('');
		
		if(!settings){settings={};}
		
		var run = function(passingThis){
			
			if(settings.anchoredClassName){
				var $anchorClassName = $('.'+settings.anchoredClassName);
				$anchorClassName.fadeOut('fast',function(){
					if($.fn.draggable){
						$anchorClassName.draggable('destory').trigger("unload").remove();	
					}else{
						$anchorClassName.trigger("unload").remove();
					}
				});
				if(settings.functionCallOnClose){settings.functionCallAfterClose();}
			}else{
				var $DOMWindowOverlay = $('#DOMWindowOverlay');
				var $DOMWindow = $('#DOMWindow');
				$DOMWindowOverlay.fadeOut('fast',function(){
					$DOMWindowOverlay.trigger('unload').unbind().remove();																	  
				});
				$DOMWindow.fadeOut('fast',function(){
					if($.fn.draggable){
						$DOMWindow.draggable("destroy").trigger("unload").remove();
					}else{
						$DOMWindow.trigger("unload").remove();
					}
				});
			
				$(window).unbind('scroll.DOMWindow');
				$(window).unbind('resize.DOMWindow');
				
				if($.fn.openDOMWindow.isIE6){$('#DOMWindowIE6FixIframe').remove();}
				if(settings.functionCallOnClose){settings.functionCallAfterClose();}
			}	
		};
		
		if(settings.eventType){//if used with $().
			return this.each(function(index){
				$(this).bind(settings.eventType, function(){
					run(this);
					return false;
				});
			});
		}else{//else called as $.function
			run();
		}
		
	};
	
	//allow for public call, pass settings
	$.closeDOMWindow = function(s){$.fn.closeDOMWindow(s);};
	
	//openDOMWindow
	$.fn.openDOMWindow = function(instanceSettings){	
		
		var shortcut =  $.fn.openDOMWindow;
	
		//default settings combined with callerSettings////////////////////////////////////////////////////////////////////////
		
		shortcut.defaultsSettings = {
			anchoredClassName:'',
			anchoredSelector:'',
			borderColor:'#ccc',
			borderSize:'4',
			draggable:0,
			eventType:null, //click, blur, change, dblclick, error, focus, load, mousedown, mouseout, mouseup etc...
			fixedWindowY:100,
			functionCallOnOpen:null,
			functionCallOnClose:null,
			height:500,
			loader:0,
			loaderHeight:0,
			loaderImagePath:'',
			loaderWidth:0,
			modal:0,
			overlay:1,
			overlayColor:'#000',
			overlayOpacity:'85',
			positionLeft:0,
			positionTop:0,
			positionType:'centered', // centered, anchored, absolute, fixed
			width:500, 
			windowBGColor:'#fff',
			windowBGImage:null, // http path
			windowHTTPType:'get',
			windowPadding:10,
			windowSource:'inline', //inline, ajax, iframe
			windowSourceID:'',
			windowSourceURL:'',
			windowSourceAttrURL:'href'
		};
		
		var settings = $.extend({}, $.fn.openDOMWindow.defaultsSettings , instanceSettings || {});
		
		//Public functions
		
		shortcut.viewPortHeight = function(){ return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;};
		shortcut.viewPortWidth = function(){ return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;};
		shortcut.scrollOffsetHeight = function(){ return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;};
		shortcut.scrollOffsetWidth = function(){ return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;};
		shortcut.isIE6 = typeof document.body.style.maxHeight === "undefined";
		
		//Private Functions/////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		var sizeOverlay = function(){
			var $DOMWindowOverlay = $('#DOMWindowOverlay');
			if(shortcut.isIE6){//if IE 6
				var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
				var overlayViewportWidth = document.documentElement.offsetWidth - 21;
				$DOMWindowOverlay.css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
			}else{//else Firefox, safari, opera, IE 7+
				$DOMWindowOverlay.css({'height':'100%','width':'100%','position':'fixed'});
			}	
		};
		
		var sizeIE6Iframe = function(){
			var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
			var overlayViewportWidth = document.documentElement.offsetWidth - 21;
			$('#DOMWindowIE6FixIframe').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
		};
		
		var centerDOMWindow = function() {
			var $DOMWindow = $('#DOMWindow');
			if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
				$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
			}else{
				$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
				$DOMWindow.css('top',Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindow.outerHeight())/2));
			}
		};
		
		var centerLoader = function() {
			var $DOMWindowLoader = $('#DOMWindowLoader');
			if(shortcut.isIE6){//if IE 6
				$DOMWindowLoader.css({'left':Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindowLoader.innerWidth())/2),'position':'absolute'});
				$DOMWindowLoader.css({'top':Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindowLoader.innerHeight())/2),'position':'absolute'});
			}else{
				$DOMWindowLoader.css({'left':'50%','top':'50%','position':'fixed'});
			}
			
		};
		
		var fixedDOMWindow = function(){
			var $DOMWindow = $('#DOMWindow');
			$DOMWindow.css('left', settings.positionLeft + shortcut.scrollOffsetWidth());
			$DOMWindow.css('top', + settings.positionTop + shortcut.scrollOffsetHeight());
		};
		
		var showDOMWindow = function(instance){
			if(arguments[0]){
				$('.'+instance+' #DOMWindowLoader').remove();
				$('.'+instance+' #DOMWindowContent').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
				$('.'+instance+ '.closeDOMWindow').click(function(){
					$.closeDOMWindow();	
					return false;
				});
			}else{
				$('#DOMWindowLoader').remove();
				$('#DOMWindow').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
				$('#DOMWindow .closeDOMWindow').click(function(){						
					$.closeDOMWindow();
					return false;
				});
			}
			
		};
		
		var urlQueryToObject = function(s){
			  var query = {};
			  s.replace(/b([^&=]*)=([^&=]*)b/g, function (m, a, d) {
				if (typeof query[a] != 'undefined') {
				  query[a] += ',' + d;
				} else {
				  query[a] = d;
				}
			  });
			  return query;
		};
			
		//Run Routine ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
		var run = function(passingThis){
			
			//get values from element clicked, or assume its passed as an option
			settings.windowSourceID = $(passingThis).attr('href') || settings.windowSourceID;
			settings.windowSourceURL = $(passingThis).attr(settings.windowSourceAttrURL) || settings.windowSourceURL;
			settings.windowBGImage = settings.windowBGImage ? 'background-image:url('+settings.windowBGImage+')' : '';
			var urlOnly, urlQueryObject;
			
			if(settings.positionType == 'anchored'){//anchored DOM window
				
				var anchoredPositions = $(settings.anchoredSelector).position();
				var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
				var anchoredPositionY = anchoredPositions.top + settings.positionTop;
				
				$('body').append('<div class="'+settings.anchoredClassName+'" style="'+settings.windowBGImage+';background-repeat:no-repeat;padding:'+settings.windowPadding+'px;overflow:auto;position:absolute;top:'+anchoredPositionY+'px;left:'+anchoredPositionX+'px;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+';z-index:10001"><div id="DOMWindowContent" style="display:none"></div></div>');		
				//loader
				if(settings.loader && settings.loaderImagePath !== ''){
					$('.'+settings.anchoredClassName).append('<div id="DOMWindowLoader" style="width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
					
				}

				if($.fn.draggable){
					if(settings.draggable){$('.' + settings.anchoredClassName).draggable({cursor:'move'});}
				}
				
				switch(settings.windowSource){
					case 'inline'://////////////////////////////// inline //////////////////////////////////////////
						$('.' + settings.anchoredClassName+" #DOMWindowContent").append($(settings.windowSourceID).children());
						$('.' + settings.anchoredClassName).unload(function(){// move elements back when you're finished
							$('.' + settings.windowSourceID).append( $('.' + settings.anchoredClassName+" #DOMWindowContent").children());				
						});
						showDOMWindow(settings.anchoredClassName);
					break;
					case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
						$('.' + settings.anchoredClassName+" #DOMWindowContent").append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" class="'+settings.anchoredClassName+'Iframe" ></iframe>');
						$('.'+settings.anchoredClassName+'Iframe').load(showDOMWindow(settings.anchoredClassName));
					break;
					case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////	
						if(settings.windowHTTPType == 'post'){
							
							if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
								urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
								urlQueryObject = urlQueryToObject(settings.windowSourceURL);
							}else{
								urlOnly = settings.windowSourceURL;
								urlQueryObject = {};
							}
							$('.' + settings.anchoredClassName+" #DOMWindowContent").load(urlOnly,urlQueryObject,function(){
								showDOMWindow(settings.anchoredClassName);
							});
						}else{
							if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
								settings.windowSourceURL += '?';
							}
							$('.' + settings.anchoredClassName+" #DOMWindowContent").load(
								settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
								showDOMWindow(settings.anchoredClassName);
							});
						}
					break;
				}
				
			}else{//centered, fixed, absolute DOM window
				
				//overlay & modal
				if(settings.overlay){
					$('body').append('<div id="DOMWindowOverlay" style="z-index:10000;display:none;position:absolute;top:0;left:0;background-color:'+settings.overlayColor+';filter:alpha(opacity='+settings.overlayOpacity+');-moz-opacity: 0.'+settings.overlayOpacity+';opacity: 0.'+settings.overlayOpacity+';"></div>');
					if(shortcut.isIE6){//if IE 6
						$('body').append('<iframe id="DOMWindowIE6FixIframe"  src="blank.html"  style="width:100%;height:100%;z-index:9999;position:absolute;top:0;left:0;filter:alpha(opacity=0);"></iframe>');
						sizeIE6Iframe();
					}
					sizeOverlay();
					var $DOMWindowOverlay = $('#DOMWindowOverlay');
					$DOMWindowOverlay.fadeIn('fast');
					if(!settings.modal){$DOMWindowOverlay.click(function(){$.closeDOMWindow();});}
				}
				
				//loader
				if(settings.loader && settings.loaderImagePath !== ''){
					$('body').append('<div id="DOMWindowLoader" style="z-index:10002;width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
					centerLoader();
				}

				//add DOMwindow
				$('body').append('<div id="DOMWindow" style="background-repeat:no-repeat;'+settings.windowBGImage+';overflow:auto;padding:'+settings.windowPadding+'px;display:none;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+'; position:absolute;z-index:10001"></div>');
				
				var $DOMWindow = $('#DOMWindow');
				//centered, absolute, or fixed
				switch(settings.positionType){
					case 'centered':
						centerDOMWindow();
						if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
							$DOMWindow.css('top', (settings.fixedWindowY + shortcut.scrollOffsetHeight()) + 'px');
						}
					break;
					case 'absolute':
						$DOMWindow.css({'top':(settings.positionTop+shortcut.scrollOffsetHeight())+'px','left':(settings.positionLeft+shortcut.scrollOffsetWidth())+'px'});
						if($.fn.draggable){
							if(settings.draggable){$DOMWindow.draggable({cursor:'move'});}
						}
					break;
					case 'fixed':
						fixedDOMWindow();
					break;
					case 'anchoredSingleWindow':
						var anchoredPositions = $(settings.anchoredSelector).position();
						var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
						var anchoredPositionY = anchoredPositions.top + settings.positionTop;
						$DOMWindow.css({'top':anchoredPositionY + 'px','left':anchoredPositionX+'px'});
								
					break;
				}
				
				$(window).bind('scroll.DOMWindow',function(){
					if(settings.overlay){sizeOverlay();}
					if(shortcut.isIE6){sizeIE6Iframe();}
					if(settings.positionType == 'centered'){centerDOMWindow();}
					if(settings.positionType == 'fixed'){fixedDOMWindow();}
				});

				$(window).bind('resize.DOMWindow',function(){
					if(shortcut.isIE6){sizeIE6Iframe();}
					if(settings.overlay){sizeOverlay();}
					if(settings.positionType == 'centered'){centerDOMWindow();}
				});
				
				switch(settings.windowSource){
					case 'inline'://////////////////////////////// inline //////////////////////////////////////////
						$DOMWindow.append($(settings.windowSourceID).children());
						$DOMWindow.unload(function(){// move elements back when you're finished
							$(settings.windowSourceID).append($DOMWindow.children());				
						});
						showDOMWindow();
					break;
					case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
						$DOMWindow.append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" id="DOMWindowIframe" ></iframe>');
						$('#DOMWindowIframe').load(showDOMWindow());
					break;
					case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
						if(settings.windowHTTPType == 'post'){
							
							if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
								urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
								urlQueryObject = urlQueryToObject(settings.windowSourceURL);
							}else{
								urlOnly = settings.windowSourceURL;
								urlQueryObject = {};
							}
							$DOMWindow.load(urlOnly,urlQueryObject,function(){
								showDOMWindow();
							});
						}else{
							if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
								settings.windowSourceURL += '?';
							}
							$DOMWindow.load(
								settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
								showDOMWindow();
							});
						}
					break;
				}
				
			}//end if anchored, or absolute, fixed, centered
			
		};//end run()
		
		if(settings.eventType){//if used with $().
			return this.each(function(index){				  
				$(this).bind(settings.eventType,function(){
					run(this);
					return false;
				});
			});	
		}else{//else called as $.function
			run();
		}
		
	};//end function openDOMWindow
	
	//allow for public call, pass settings
	$.openDOMWindow = function(s){$.fn.openDOMWindow(s);};
	
})(jQuery);

/* regulate the slider new style 
perslider is called on a div with an ul with 1 to n li + thumbnails and appended with two scroller arrows if needed, each thumbnail is given some behavior, as well as the arrows
*/
(function($) {
    $.fn.extend({
        perSlider: function(options) 
		{
			/* ie doesnt size the devils, since they are not visible or not loaded when sizing */
			$('#album-tn-nav li a.viewer-thumb span.imgwrap').css({width:'83px',height:'62px'});
			//alert('slider');
			
			return this.each(function() {

			var obj = $(this); // the div

			var defaults = {
			limit: 4
			};
			var options = $.extend(defaults, options);	
		
		
		
			var items = $('li', obj);
			
			if( items.length > 4 )
			{
				$('li:gt(3)', obj).addClass('hidden');
				obj.prepend('<span class="viewer-navigate-button navprev"><span>previous</span></span>');
				obj.append('<span class="viewer-navigate-button navnext"><span>next</span></span>');
			}
			
			$('.viewer-navigate-button', obj).click(function()
			{
				if( $(this).hasClass('navnext'))
				{
					$('li.tn_next', obj).click();
				}
				else
				{
					$('li.tn_prev', obj).click();
				}
	
			});
			
			items.click(function(event){
				
				event.preventDefault();
				
				var indexthis = $("li", obj).index(this);
				
				if ( $(this).hasClass('hidden') )
				{
					// show this one, hide nr -3
					$(this).removeClass('hidden');
					if ( $(this).hasClass('tn_next') )
					{
						indexhide = parseInt(indexthis) - 3;
						$('li:lt('+indexhide+')', obj).addClass('hidden');
					}
					else if ( $(this).hasClass('tn_prev') )
					{
						indexhide = parseInt(indexthis) + 3;
						$('li:gt('+indexhide+')', obj).addClass('hidden');
					}
				}
				$('#signposts-currentalbum .current-nr').html(parseInt(indexthis)+1);
				
				$('li', obj).removeClass('tn_current').removeClass('tn_next').removeClass('tn_prev');
				$(this).addClass('tn_current');
				$(this).next('li').addClass('tn_next');
				$(this).prev('li').addClass('tn_prev');
				
				var ctitle = $('a',this).attr('title');
				//.toUpperCase()
				//alert(ctitle);
				var href = $('a',this).attr('href');
				// the parent is the viewer-block
				var viewbig = $(this).parents('.album-viewer-block').find('.viewbig');
				var header = $(this).parents('.album-viewer-block').find('h3:first');
				header.html(ctitle);
				viewbig.html('');
				
				if( href.indexOf('.flv') == -1 )
				{
					st = 'width:495px; height:330px; background:#FFF url('+href+')';
					var rimage = $('<span class="imgwrap" style="'+st+'"></span>');
					rimage.fadeOut().appendTo(viewbig).fadeIn('slow');
				}
				else
				{
					var fmovie = $('<object width="495" height="330" name="player" id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="/flvplayer/jw51/player.swf" name="movie"/><param value="true" name="allowfullscreen"><param value="always" name="allowscriptaccess"><param value="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50" name="flashvars"><embed name="player1" id="player2" width="495" height="300" allowfullscreen="true" allowscriptaccess="always"  type="application/x-shockwave-flash" src="/flvplayer/jw51/player.swf" flashvars="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50"/></object>');
					fmovie.appendTo(viewbig);
				}
								 
			});

			items.eq(0).click();
			
			});
        }
    });
})(jQuery);



/* Style buttons */
(function($) {
    
    $.fn.stylesubmitbuttons = function() {
		
		$('input.submitbutton-regular', this).each(
			function(){
				if($(this).hasClass('replaced')) {return;}
				
				var showtext = $(this).val();
				var buttonid = $(this).attr('id');
				$(this).before('<a class="button replaced-input-submit" href="#'+buttonid+'"><span>'+showtext+'</span></a>');
				$(this).css('margin-left','-3000px').addClass('replaced');
			}									 
		);
		
		$('input.submitbutton-small', this).each(
			function(){
				if($(this).hasClass('replaced')) {return;}
				
				var showtext = $(this).val();
				var buttonid = $(this).attr('id');
				$(this).before('<a class="smallbutton replaced-input-submit" href="#'+buttonid+'"><span>'+showtext+'</span></a>');
				$(this).css('margin-left','-3000px').addClass('replaced');
			
			}									 
		);
		
		$('input.submitbutton-nega', this).each(
			function(){
				if($(this).hasClass('replaced')) {return;}
				var showtext = $(this).val();
				var buttonid = $(this).attr('id');
				$(this).before('<a class="negabutton replaced-input-submit" href="#'+buttonid+'"><span>'+showtext+'</span></a>');
				$(this).css('margin-left','-3000px').addClass('replaced');
			}									 
		);
		
		$('a.replaced-input-submit', this).each(function()
		{
			if($(this).hasClass('withsubmithandler')) {return;}
			$(this).bind('click', function(event)
			{
				event.preventDefault();
				//alert(buttonid);
				var href = $(this).attr('href');
				var buttonid = href.split('#')[1];
				$('#'+buttonid).click();
			});
			$(this).addClass('withsubmithandler');
		});
		
	};
		

		
})(jQuery);		


/**/


/*
 *
 * jqTransform
 * by mathieu vilaplana mvilaplana@dfc-e.com
 * Designer ghyslain armand garmand@dfc-e.com
 *
 *
 * Version 1.0 25.09.08
 * Version 1.1 06.08.09
 * Add event click on Checkbox and Radio
 * Auto calculate the size of a select element
 * Can now, disabled the elements
 * Correct bug in ff if click on select (overflow=hidden)
 * No need any more preloading !!
 * 
 ******************************************** */
 
(function($){
	var defaultOptions = {preloadImg:true};
	var jqTransformImgPreloaded = false;

	var jqTransformPreloadHoverFocusImg = function(strImgUrl) {
		//guillemets to remove for ie
		strImgUrl = strImgUrl.replace(/^url\((.*)\)/,'$1').replace(/^\"(.*)\"$/,'$1');
		var imgHover = new Image();
		imgHover.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-hover.$1');
		var imgFocus = new Image();
		imgFocus.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-focus.$1');				
	};

	
	/***************************
	  Labels
	***************************/
	var jqTransformGetLabel = function(objfield){
		var selfForm = $(objfield.get(0).form);
		var oLabel = objfield.next();
		if(!oLabel.is('label')) {
			oLabel = objfield.prev();
			if(oLabel.is('label')){
				var inputname = objfield.attr('id');
				if(inputname){
					oLabel = selfForm.find('label[for="'+inputname+'"]');
				} 
			}
		}
		if(oLabel.is('label')){return oLabel.css('cursor','pointer');}
		return false;
	};
	
	/* Hide all open selects */
	var jqTransformHideSelect = function(oTarget){
		var ulVisible = $('.jqTransformSelectWrapper ul:visible');
		ulVisible.each(function(){
			var oSelect = $(this).parents(".jqTransformSelectWrapper:first").find("select").get(0);
			//do not hide if click on the label object associated to the select
			if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){$(this).hide();}
		});
	};
	/* Check for an external click */
	var jqTransformCheckExternalClick = function(event) {
		if ($(event.target).parents('.jqTransformSelectWrapper').length === 0) { jqTransformHideSelect($(event.target)); }
	};

	/* Apply document listener */
	var jqTransformAddDocumentListener = function (){
		$(document).mousedown(jqTransformCheckExternalClick);
	};	
			
	/* Add a new handler for the reset action */
	var jqTransformReset = function(f){
		var sel;
		$('.jqTransformSelectWrapper select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
		$('a.jqTransformCheckbox, a.jqTransformRadio', f).removeClass('jqTransformChecked');
		$('input:checkbox, input:radio', f).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jqTransformChecked');}});
	};


	/***************************
	  Check Boxes 
	 ***************************/	
	$.fn.jqTransCheckBox = function(){
		return this.each(function(){
			if($(this).hasClass('jqTransformHidden')) {return;}

			var $input = $(this);
			var inputSelf = this;

			//set the click on the label
			var oLabel=jqTransformGetLabel($input);
			oLabel && oLabel.click(function(){aLink.trigger('click');});
			
			var aLink = $('<a href="#" class="jqTransformCheckbox"></a>');
			//wrap and add the link
			$input.addClass('jqTransformHidden').wrap('<span class="jqTransformCheckboxWrapper"></span>').parent().prepend(aLink);
			//on change, change the class of the link
			$input.change(function(){
				this.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked');
				return true;
			});
			// Click Handler, trigger the click and change event on the input
			aLink.click(function(){
				//do nothing if the original input is disabled
				if($input.attr('disabled')){return false;}
				//trigger the envents on the input object
				$input.trigger('click').trigger("change");	
				return false;
			});

			// set the default state
			this.checked && aLink.addClass('jqTransformChecked');		
		});
	};
	/***************************
	  Radio Buttons 
	 ***************************/	
	$.fn.jqTransRadio = function(){
		return this.each(function(){
			if($(this).hasClass('jqTransformHidden')) {return;}
			
			var buttonid = $(this).attr('id');
			var aLink = $('<a class="jqTransformRadio" href="#'+buttonid+'" rel="'+$(this).attr('name')+'"></a>');
			$(this).before(aLink);
			$(this).css('margin-left','-3000px').addClass('replaced jqTransformHidden');		
				
			// set the default state
			if( this.checked )
			{
				$('a[href=#'+buttonid+']').addClass('jqTransformChecked');
			}


			// Click Handler
			aLink.click(function(event){
				event.preventDefault();
				//alert(buttonid);
				var href = $(this).attr('href');
				var buttonid = href.split('#')[1];
				$('#'+buttonid).click();				
			});

			$(this).click(function()
				{
					var buttonid = $(this).attr('id');
					var name = $(this).attr('name');
					$('a[rel="'+name+'"]').removeClass('jqTransformChecked');
					$('a[href=#'+buttonid+']').addClass('jqTransformChecked');
				}
			);
				
			
		});
	};
	
	
	/***************************
	  Select 
	 ***************************/	
	$.fn.jqTransSelect = function(){
		return this.each(function(index){
			var $select = $(this);

			if($select.hasClass('jqTransformHidden')) {return;}
			if($select.attr('multiple')) {return;}

			var oLabel  =  jqTransformGetLabel($select);
			/* First thing we do is Wrap it */
			var $wrapper = $select
				.addClass('jqTransformHidden')
				.wrap('<div class="jqTransformSelectWrapper"></div>')
				.parent()
				.css({zIndex: 1000-index})
			;
			
			/* Now add the html for the select */
			$wrapper.prepend('<div><span></span><a href="#" class="jqTransformSelectOpen"></a></div><ul></ul>');
			//var $ul = $('ul', $wrapper).css('width',$select.width()).hide();
			var $ul = $('ul', $wrapper).css('width',160).hide();
			/* Now we add the options */
			$('option', this).each(function(i){
				var oLi = $('<li><a class="opt'+i+'" href="#" index="'+ i +'">'+ $(this).html() +'</a></li>');
				$ul.append(oLi);
			});
			
			/* Add click handler to the a */
			$ul.find('a').click(function(){
					$('a.selected', $wrapper).removeClass('selected');
					$(this).addClass('selected');	
					/* Fire the onchange event */
					if ($select[0].selectedIndex != $(this).attr('index')) 
					{ 
					$select[0].selectedIndex = $(this).attr('index'); 
					$select.change();
					}
					
					$select[0].selectedIndex = $(this).attr('index');
					
					$('span:eq(0)', $wrapper).html($(this).html());
					$ul.hide();
					return false;
			});
			/* Set the default */
			$('a:eq('+ this.selectedIndex +')', $ul).click();
			$('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
			oLabel && oLabel.click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
			this.oLabel = oLabel;
			
			/* Apply the click handler to the Open */
			var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
				.click(function(){
					//Check if box is already open to still allow toggle, but close all other selects
					if( $ul.css('display') == 'none' ) {jqTransformHideSelect();} 
					if($select.attr('disabled')){return false;}

					$ul.slideToggle('fast', function(){					
						var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
						$ul.animate({scrollTop: offSet});
					});
					return false;
				})
			;

			// Set the new width
			var iSelectWidth = $select.outerWidth();
			var oSpan = $('span:first',$wrapper);
			var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
			/* override */
			newWidth = 152;
			$wrapper.css('width',newWidth);
			$ul.css('width',newWidth-2);
			oSpan.css({width:iSelectWidth});
		
			// Calculate the height if necessary, less elements that the default height
			//show the ul to calculate the block, if ul is not displayed li height value is 0
			$ul.css({display:'block',visibility:'hidden'});
			var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
			(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
			$ul.css({display:'none',visibility:'visible'});
			
		});
	};
	
	$.fn.jqTransform = function(options){
		var opt = $.extend({},defaultOptions,options);
		
		/* each form */
		 return this.each(function(){
			var selfForm = $(this);
			if(selfForm.hasClass('jqtransformdone')) {return;}
			selfForm.addClass('jqtransformdone');
			
			//$('input:submit, input:reset, input[type="button"]', this).jqTransInputButton();			
			//$('input:text, input:password', this).jqTransInputText();			
			$('input:checkbox', this).jqTransCheckBox();
			$('input:radio', this).jqTransRadio();
			//$('textarea', this).jqTransTextarea();
			
			if( $('select', this).jqTransSelect().length > 0 ){jqTransformAddDocumentListener();}
			selfForm.bind('reset',function(){var action = function(){jqTransformReset(this);}; window.setTimeout(action, 10);});
			
			//preloading dont needed anymore since normal, focus and hover image are the same one
			/*if(opt.preloadImg && !jqTransformImgPreloaded){
				jqTransformImgPreloaded = true;
				var oInputText = $('input:text:first', selfForm);
				if(oInputText.length > 0){
					//pour ie on eleve les ""
					var strWrapperImgUrl = oInputText.get(0).wrapper.css('background-image');
					jqTransformPreloadHoverFocusImg(strWrapperImgUrl);					
					var strInnerImgUrl = $('div.jqTransformInputInner',$(oInputText.get(0).wrapper)).css('background-image');
					jqTransformPreloadHoverFocusImg(strInnerImgUrl);
				}
				
				var oTextarea = $('textarea',selfForm);
				if(oTextarea.length > 0){
					var oTable = oTextarea.get(0).oTable;
					$('td',oTable).each(function(){
						var strImgBack = $(this).css('background-image');
						jqTransformPreloadHoverFocusImg(strImgBack);
					});
				}
			}*/
			
			
		}); /* End Form each */
				
	};/* End the Plugin */

})(jQuery);
				   


/*
 * Style File - jQuery plugin for styling file input elements
 *  
 * Copyright (c) 2007-2008 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Based on work by Shaun Inman
 *   http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
 *
 * Revision: $Id: jquery.filestyle.js 303 2008-01-30 13:53:24Z tuupola $
 *
 */

(function($) {
    
    $.fn.filestyle = function(options) {
                
        /* TODO: This should not override CSS. */
        var settings = {
            width : 250
        };
                
        if(options) {
            $.extend(settings, options);
        };
                        
        return this.each(function() {
            
            var self = this;
            var wrapper = $("<div>")
                            .css({
                                "width": settings.imagewidth + "px",
                                "height": settings.imageheight + "px",
                                "background": "url(" + settings.image + ") 0 0 no-repeat",
                                "background-position": "right",
								"padding" : "0",
								"margin-left" : "11px",
                                "display": "inline",
                                "position": "absolute",
                                "overflow": "hidden"
                            });
                            
            var filename = $('<input class="file">')
                             .addClass($(self).attr("class"))
                             .css({
                                 "display": "inline",
                                 "width": settings.width + "px"
                             });

            $(self).before(filename);
            $(self).wrap(wrapper);

            $(self).css({
                        "position": "relative",
                        "height": settings.imageheight + "px",
                        "width": settings.width + "px",
                        "display": "inline",
                        "cursor": "pointer",
                        "opacity": "0.0"
                    });

            if ($.browser.mozilla) {
                if (/Win/.test(navigator.platform)) {
                    $(self).css("margin-left", "-142px");                    
                } else {
                    $(self).css("margin-left", "-168px");                    
                };
            } else {
                $(self).css("margin-left", settings.imagewidth - settings.width + "px");                
            };

            $(self).bind("change", function() {
                filename.val($(self).val());
            });
      
        });
        

    };
    
})(jQuery);







/* ========
Utilities
*/
function randOrd(){
return (Math.round(Math.random())-0.5); } 

/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
;(function(){
	
var $$;

/**
 * 
 * @desc Replace matching elements with a flash movie.
 * @author Luke Lutman
 * @version 1.0.1
 *
 * @name flash
 * @param Hash htmlOptions Options for the embed/object tag.
 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
 * @param Function replace Custom block called for each matched element if flash is installed (optional).
 * @param Function update Custom block called for each matched if flash isn't installed (optional).
 * @type jQuery
 *
 * @cat plugins/flash
 * 
 * @example $('#hello').flash({ src: 'hello.swf' });
 * @desc Embed a Flash movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
 * @desc Embed a Flash 8 movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
 * @desc Embed a Flash movie using Express Install if flash isn't installed.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
 *
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
	
	// Set the default block.
	var block = replace || $$.replace;
	
	// Merge the default and passed plugin options.
	pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
	
	// Detect Flash.
	if(!$$.hasFlash(pluginOptions.version)) {
		// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
		if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
			// Add the necessary flashvars (merged later).
			var expressInstallOptions = {
				flashvars: {  	
					MMredirectURL: location,
					MMplayerType: 'PlugIn',
					MMdoctitle: jQuery('title').text() 
				}					
			};
		// Ask the user to update (if specified).
		} else if (pluginOptions.update) {
			// Change the block to insert the update message instead of the flash movie.
			block = update || $$.update;
		// Fail
		} else {
			// The required version of flash isn't installed.
			// Express Install is turned off, or flash 6,0,65 isn't installed.
			// Update is turned off.
			// Return without doing anything.
			return this;
		}
	}
	
	// Merge the default, express install and passed html options.
	htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
	
	// Invoke $block (with a copy of the merged html options) for each element.
	return this.each(function(){
		block.call(this, $$.copy(htmlOptions));
	});
	
};
/**
 *
 * @name flash.copy
 * @desc Copy an arbitrary number of objects into a new object.
 * @type Object
 * 
 * @example $$.copy({ foo: 1 }, { bar: 2 });
 * @result { foo: 1, bar: 2 };
 *
**/
$$.copy = function() {
	var options = {}, flashvars = {};
	for(var i = 0; i < arguments.length; i++) {
		var arg = arguments[i];
		if(arg == undefined) continue;
		jQuery.extend(options, arg);
		// don't clobber one flash vars object with another
		// merge them instead
		if(arg.flashvars == undefined) continue;
		jQuery.extend(flashvars, arg.flashvars);
	}
	options.flashvars = flashvars;
	return options;
};
/*
 * @name flash.hasFlash
 * @desc Check if a specific version of the Flash plugin is installed
 * @type Boolean
 *
**/
$$.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $$.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};
/**
 *
 * @name flash.hasFlash.playerVersion
 * @desc Get the version of the installed Flash plugin.
 * @type String
 *
**/
$$.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};
/**
 *
 * @name flash.htmlOptions
 * @desc The default set of options for the object or embed tag.
 *
**/
$$.htmlOptions = {
	height: 240,
	wmode: 'opaque',
	flashvars: {},
	pluginspage: 'http://www.adobe.com/go/getflashplayer',
	src: '#',
	type: 'application/x-shockwave-flash',
	width: 320		
};
/**
 *
 * @name flash.pluginOptions
 * @desc The default set of options for checking/updating the flash Plugin.
 *
**/
$$.pluginOptions = {
	expressInstall: false,
	update: true,
	version: '6.0.65'
};
/**
 *
 * @name flash.replace
 * @desc The default method for replacing an element with a Flash movie.
 *
**/
$$.replace = function(htmlOptions) {
	this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
	jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
};
/**
 *
 * @name flash.update
 * @desc The default method for replacing an element with an update message.
 *
**/
$$.update = function(htmlOptions) {
	var url = String(location).split('?');
	url.splice(1,0,'?hasFlash=true&');
	url = url.join('');
	var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
	this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
	jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
};
/**
 *
 * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
 * @example toAttributeString.apply(htmlOptions)
 * @result foo="bar" foo="bar"
 *
**/
function toAttributeString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'="'+this[key]+'" ';
	return s;		
};
/**
 *
 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
 * @example toFlashvarsString.apply(flashvarsObject)
 * @result foo=bar&foo=bar
 *
**/
function toFlashvarsString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'='+encodeURIComponent(this[key])+'&';
	return s.replace(/&$/, '');		
};
/**
 *
 * @name flash.transform
 * @desc Transform a set of html options into an embed tag.
 * @type String 
 *
 * @example $$.transform(htmlOptions)
 * @result <embed src="foo.swf" ... />
 *
 * Note: The embed tag is NOT standards-compliant, but it 
 * works in all current browsers. flash.transform can be
 * overwritten with a custom function to generate more 
 * standards-compliant markup.
 *
**/
$$.transform = function(htmlOptions) {
	htmlOptions.toString = toAttributeString;
	if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
	return '<EMBED ' + String(htmlOptions) + '/>';		
};

/**
 *
 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
 *
**/
if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function(){
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}
	
})();


/*********************************************************************************************************
FauxColumnheights trekt bepaalde blokken op gelijke hoogte
*/
	jQuery.fn.fauxColumnHeights=function(columns)
	{
		var total=$(this).length;
		var maxRowHeight=0;
		var allElements=$(this);
		$(this).each(function(index)
		{
			var hindex=index+1;
			var theight=$(this).height();
			if(theight>maxRowHeight)
			{
				maxRowHeight=theight;
			}
			if(parseInt(hindex/columns)==parseFloat(hindex/columns))
			{
				for(i=0;i<columns;i++)
				{
					$(allElements[index-i]).css('min-height', maxRowHeight+3+'px').addClass('adjusted');
				}
				maxRowHeight=0;
			}
			if(total==hindex)
			{
				$(allElements).not('.adjusted').each(function()
				{
					$(this).css('min-height', maxRowHeight+3+'px').addClass('adjusted');
				});
		}});
	}


/*********************************************************************************************************
Form validation old style
*/

function validateForms() {
	var forms = document.forms;
	for (var i=0;i<forms.length;i++) {
		forms[i].onsubmit = validate;
	}
}



var validationErrorMessage = new Object();
validationErrorMessage['required'] = 'Dit veld is verplicht';
validationErrorMessage['numeric'] = "Dit moet een getal zijn";
validationErrorMessage['postcode'] = 'Dit moet een Nederlandse postcode zijn';
validationErrorMessage['pattern'] = 'Patroon klopt niet';
validationErrorMessage['email'] = 'Dit emailadres is incorrect';

var validationFunctions = new Object();
validationFunctions["required"] = isRequired;
validationFunctions["pattern"] = isPattern;
validationFunctions["postcode"] = isPostCode;
validationFunctions["numeric"] = isnumeric;
validationFunctions["email"] = isEmail;

function isRequired(formField) {
	switch (formField.type) {
		case 'text':
		case 'textarea':
		case 'select-one':
			if (formField.value)
				return true;
			return false;
		case 'radio':
			var radios = formField.form[formField.name];
			for (var i=0;i<radios.length;i++) {
				if (radios[i].checked) return true;
			}
			return false;
		case 'checkbox':
			return formField.checked;
	}	
}

function isPattern(formField,pattern) {
	var pattern = pattern || formField.getAttribute('pattern');
	var regExp = new RegExp("^"+pattern+"$","");
	var correct = regExp.test(formField.value);
	if (!correct && formField.getAttribute('patternDesc'))
		correct = formField.getAttribute('patternDesc');
	return correct;
}

function isPostCode(formField) {
	return isPattern(formField,"\\d{4}\\s*\\D{2}");
}

function isnumeric(formField) {
	return isPattern(formField,"\\d+");
}

/* loopt vast op punten uin adressen
function isEmail(formField) {
	return isPattern(formField,"\\w*@\\w*\.\\w{2,4}")
}
function isEmail(formField) {
   var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if (regex.test(email)) return true;
   else return false;
}
*/
function isEmail(formField) {
	//alert(formField.value);
	   var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if (regex.test(formField.value)) return true;
   else return false;
}

function emptyFunction() {
	return true;
}

/*********************************/

function validate() {
	// when form is being submitted, skip. this dynamiclay added classname is cleared when ff reacts on backbutton.
	if( $(this).hasClass('submitting') )
	{
		return false;
	}
	else
	{
		
		var els = this.elements;
		var validForm = true;
		var firstError = null;
		for (var i=0;i<els.length;i++) {
			if (els[i].removeError)
				els[i].removeError();
			var req = els[i].className;
			// classname
			//alert(req);
			if (!req) continue;
			var reqs = req.split(' ');
			if (els[i].getAttribute('pattern'))
				reqs[reqs.length] = 'pattern';
			for (var j=0;j<reqs.length;j++) {
				if (!validationFunctions[reqs[j]])
					validationFunctions[reqs[j]] = emptyFunction;
				var OK = validationFunctions[reqs[j]](els[i]);
				if (OK != true) {
					var errorMessage = OK || validationErrorMessage[reqs[j]];
					writeError(els[i],errorMessage);
					validForm = false;
					if (!firstError)
						firstError = els[i];
					break;
				}
			}
		}
	
		if (!validForm) 
		{
			//alert("Controleer het formulier");
			//location.hash = '#startOfForm';
			$('#authenticatiecode').hide();
			
			for (var i=0;i<els.length;i++) {
				if (els[i].type == 'submit')
				{
					els[i].disabled=false;
				}
			}
		}
		else
		{
			// block the submit buttons
			// GH doenst work when using back button in FF
			/* therefor (i dont know any other) defaulting to technique of classnames wich can easily transparantly be recovered at onload.
			
			for (var i=0;i<els.length;i++) {
				if (els[i].type == 'submit')
				{
					els[i].disabled='disabled';
				}
			}
			*/
			$(this).addClass('submitting');
			//.css({border : '1px solid red'});
		}
		return validForm;
	}
	
}

function writeError(obj,message) {
	obj.parentNode.className += ' errorMessage';
	obj.onchange = removeError;
	if (obj.errorMessage || obj.parentNode.errorMessage) return;
	var errorMessage = document.createElement('label');
	errorMessage.className = 'errorMessage';
	errorMessage.setAttribute('for',obj.id);
	errorMessage.setAttribute('htmlFor',obj.id);
	errorMessage.appendChild(document.createTextNode(message));
	obj.parentNode.appendChild(errorMessage);
	obj.errorMessage = errorMessage;
	obj.parentNode.errorMessage = errorMessage;
}

function removeError() {
	this.parentNode.className = this.parentNode.className.replace(/errorMessage/,'');
	if (this.errorMessage) {
		this.parentNode.removeChild(this.errorMessage);
		this.errorMessage = null;
		this.parentNode.errorMessage = null;
	}
	this.onchange = null;
}

	function toggleworkingspace()
	{
		// originaal was de animator 990 x 600 
		// nu 575 x 950
		
		
		if( $('a#toggleworkingspace').hasClass('extended')  )	
		{
			$('#menus').show();
			$('#user-functions').show();
			$('#site-menu').show();
			$('#identity').show();
			$('a#toggleworkingspace').removeClass('extended');
			$('a#toggleworkingspace span').html('vergroot werkruimte');
			$('object#animator').width('950').height('575');
			$('object#animator embed').width('950').height('575');
			$('object#animator embed').css({width: 950, height:575});
			// $('#content').css({padding:0});
			$('#page').css({width:968, padding: '0'});
			
		}
		else
		{
			$('#identity').hide();
			$('#user-functions').hide();
			$('#menus').hide();
			$('#site-menu').hide();
			$('a#toggleworkingspace span').html('verklein werkruimte');
			$('a#toggleworkingspace').addClass('extended');
			
			// determine possibel width, max = 1240 for historical reasons
			
			var animwidth = $(window).width() - 40;
			if(animwidth > 1240)
			animwidth = 1240;
			
			var animheight = animwidth * 600/990;
			var available_height =  $(window).height() -50;
			if(animheight > available_height)
			{
			 // resize the other way
			 	animheight = available_height;
				animwidth = animheight * 900/600;			
			}
			
			
			//alert('new width '+animwidth);
			//alert('new height '+animheight);
			//alert()
			var pagewidth = animwidth+20;
			//alert('page = '+pagewidth);
			$('#page').css({width: pagewidth , padding: '10px 0 0 0'});
			
			$('object#animator').width(animwidth).height(animheight);
			$('object#animator').css({width: animwidth, height :animheight});
			
			$('object#animator embed').width(animwidth).height(animheight);
			$('object#animator embed').css({width: animwidth, height :animheight});
			
			//$('#content').css({padding:0});
		}		
	}


	function gup( name )
	{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return results[1];
	}

	$(window).ready(function()
	{
		
		if( gup('brochurevo') == 1 )
		{
			//alert( gup('brochurevo') );
			//alert( $('a#brochurevo').attr('href') );
			window.open( $('a#brochurevo').attr('href') );
			$('a#brochurevo').click();			
		}

		if( gup('brochurepo') == 1 )
		{
			$('a#brochurepo').click();
			window.open( $('a#brochurepo').attr('href') );
		}
	});

	$(document).ready(function()
	{
		



		$('#top-lists ul').shuffle();
	
		$('#ClipSearchForm').submit(function(){
		
			var com = $('#ClipG').val();
			//alert(com);
		
			var regExp = new RegExp("^\\d+$","");
			var correct = regExp.test(com);
			if(!correct)
			{
				return false;	
			}
			
		});
		
		$('object#animator').after('<p class="workspace-switcher"><a id="toggleworkingspace" class="nowarnings"><span>Vergroot werkruimte</span></a></p>');
		
		$('a#toggleworkingspace').click(function(){
			toggleworkingspace();		
		});
		
		if ( $('strong#qsearch').html() != '' )
		{
			$('input#t').val( $('#qsearch').html()  );
		}
		//$('select').selectbox({debug: true});
		//$('select').selectbox();
		$('#clips-view #flashMessage').click(function(){$(this).hide();});

		$('#theholyplayer').flash(
        { width: 480, height: 340 },
        { version: 8 },

			function(htmlOptions) {
				$this = $(this);
				htmlOptions.src = $this.attr('href');
				htmlOptions.wmode = 'opaque';
				htmlOptions.flashvars = { clip_id: $this.attr('rel') , autoplay: '1', repeat: '0' };
				$this.before($.fn.flash.transform(htmlOptions));
		   }

    	);
		$('#theholyplayer span').hide();
		
		$('a#showauthcode').click(function(event){
			event.preventDefault();
			$('#authenticatiecode').show();
		});
		
		$('#page #authenticatiecode h3').click(function(){
			$('#authenticatiecode').hide();
		});	
		
		$('a.flvmovie').each(function(){
									  
			var href=$(this).attr('href');
			var image = "";
			// detect preview image
			if( $('img', this).length > 0 )
			{
				image = $('img', this).attr('src');
				var fmovie = '<object width="495" height="300" name="player" id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="/flvplayer/jw51/player.swf" name="movie"/><param value="true" name="allowfullscreen"><param value="always" name="allowscriptaccess"><param value="file=' + href + '&amp;autostart=0&amp;screencolor=white&amp;repeat=always&amp;volume=50&amp;image='+image+'" name="flashvars"><embed name="player1" id="player2" width="495" height="300" allowfullscreen="true" allowscriptaccess="always"  type="application/x-shockwave-flash" src="/flvplayer/jw51/player.swf" flashvars="file=' + href + '&amp;autostart=0&amp;screencolor=white&amp;repeat=always&amp;volume=50&amp;image='+image+'"/></object>';
			}
			else
			{
				var fmovie ='<object width="495" height="300" name="player" id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="/flvplayer/jw51/player.swf" name="movie"/><param value="true" name="allowfullscreen"><param value="always" name="allowscriptaccess"><param value="file=' + href + '&amp;autostart=0&amp;screencolor=white&amp;repeat=always&amp;volume=50" name="flashvars"><embed name="player1" id="player2" width="495" height="300" allowfullscreen="true" allowscriptaccess="always"  type="application/x-shockwave-flash" src="/flvplayer/jw51/player.swf" flashvars="file=' + href + '&amp;autostart=0&amp;screencolor=white&amp;repeat=always&amp;volume=50"/></object>';
			}
									  
			  
			$(fmovie).insertBefore(this);
			$(this).hide();
		});
		
		
		
		$('a.flvmovieautoplay').each(function(){
			  var href=$(this).attr('href');
			$('<object width="495" height="300" name="player" id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="/flvplayer/jw51/player.swf" name="movie"/><param value="true" name="allowfullscreen"><param value="always" name="allowscriptaccess"><param value="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50" name="flashvars"><embed name="player1" id="player2" width="495" height="300" allowfullscreen="true" allowscriptaccess="always"  type="application/x-shockwave-flash" src="/flvplayer/jw51/player.swf" flashvars="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50"/></object>').insertBefore(this);
			$(this).hide();
		});
	/*	
		<object height="315" width="400" name="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="player">
		<param value="player.swf" name="movie">
		<param value="true" name="allowfullscreen">
		<param value="always" name="allowscriptaccess">
		<param value="file=video.flv&amp;image=preview.jpg" name="flashvars">
		<embed height="315" width="400" flashvars="file=video.flv&amp;image=preview.jpg" allowfullscreen="true" allowscriptaccess="always" src="player.swf" name="player2" id="player2" type="application/x-shockwave-flash">
	</object>
	*/	
		$('a#testholyplayer').flash(
        	{ width: 502, height:415, id:'theholyplayer', scale: 'noscale', salign : 'lt' },
        	{ version: 8 },
				function(htmlOptions) {
					$this = $(this);
					var next_clip_url = $('#next_clip_url').html();
					var respond_url = $('#clip_respond_url').html();
					
					htmlOptions.src = $this.attr('href');
					htmlOptions.wmode = 'opaque';
					htmlOptions.flashvars = { 
					clip_id: $this.attr('rel'),
					autoplay: '1',
					repeat: '0',
					holyplayer : '1',
					mute : '0',
					next_url : next_clip_url,
					react_url : respond_url
					};
				$('#view-clip .cnt').css({height:'430px'});
				setHolyPlayerContainerToInlinePosition();
				$('#holyPlayerContainer').append($.fn.flash.transform(htmlOptions));
				$('#show-do-rating').addClass('remove').clone().removeClass('remove').appendTo('#holyPlayerContainer');
				$('.remove').remove();
		   }

    	);
		$('#testholyplayer span').hide();
		
		$(window).bind('resize', function() {
			setHolyPlayerContainerToInlinePosition();
		});

		
		$('#thecarrouselplayer').flash(
        { width: 335, height: 268 },
        { version: 8 },

			function(htmlOptions) {
				$this = $(this);
				htmlOptions.src = $this.attr('href');
				htmlOptions.wmode = 'opaque';
				var selclipid = $this.attr('rel');
				if( $('#cardata').length > 0 )
				{
					// get cardata
					var clipstring = $('#cardata').html();
					if (clipstring)
					{
						clips = clipstring.split('|');
						clips.sort( randOrd );
						var selclipid = clips.join('|');
					}
				}
				//alert(selclipid);
				htmlOptions.flashvars = { clip_id: selclipid, repeatAll : 1, autoplay: '1', repeat: '0' };
				$this.before($.fn.flash.transform(htmlOptions));
		   }

    	);
		$('#thecarrouselplayer span').hide();
		
		
		$('#testsequentieplayer').flash(
        { width: 350, height: 262 , scale: 'noscale', salign : 'lt'},
        { version: 8 },

			function(htmlOptions) {
				$this = $(this);
				htmlOptions.src = $this.attr('href');
				htmlOptions.wmode = 'opaque';
				if( $('#cardata').length > 0 )
				{
					var clips = new Array();
					// get cardata
					i = 0;
					$('#cardata span.clip .clip_id').each(function(){
						clips[i]=$(this).html();
						i++;
					});
					clips.sort( randOrd );
					var selclipids = clips.join('|');
				}
				//alert(selclipid);
				htmlOptions.flashvars = { 
				clip_id: selclipids, 
				repeatAll : 1,
				mute : '1',
				autoplay: '1',
				autostart: '1',
				repeat: '0',
				sequenceplayer : '1'
				};
				$this.before($.fn.flash.transform(htmlOptions));
		   }

    	);
		$('#testsequentieplayer span').hide();
		
		$('#sequentieplayer').flash(
        { width: 350, height: 262 , scale: 'noscale', salign : 'lt'},
        { version: 8 },

			function(htmlOptions) {
				$this = $(this);
				htmlOptions.src = $this.attr('href');
				htmlOptions.wmode = 'opaque';
				if( $('#cardata').length > 0 )
				{
					var clips = new Array();
					// get cardata
					i = 0;
					$('#cardata span.clip .clip_id').each(function(){
						clips[i]=$(this).html();
						i++;
					});
					clips.sort( randOrd );
					var selclipids = clips.join('|');
				}
				//alert(selclipid);
				htmlOptions.flashvars = { 
				clip_id: selclipids, 
				repeatAll : 1,
				mute : '1',
				autoplay: '1',
				autostart: '1',
				repeat: '0',
				sequenceplayer : '1'
				};
				$this.before($.fn.flash.transform(htmlOptions));
		   }

    	);
		$('#sequentieplayer span').hide();


		$('#thespiralplayer').flash(
        { width: 480, height: 340 },
        { version: 8 },

			function(htmlOptions) {
				$this = $(this);
				htmlOptions.src = $this.attr('href');
				htmlOptions.wmode = 'opaque';
				//var group = $this.attr('rel')
				//alert(selclipid);
				htmlOptions.flashvars = { autoplay: '1', repeat: '0', bgcolor: '#FFFFFF' };
				$this.before('<div id="spiralplayer"></div>');
				$('#spiralplayer').append($.fn.flash.transform(htmlOptions));
		   }

    	);
		$('a#thespiralplayer').hide();
		
		
		$('#chatlink').click(function(event){
			
			event.preventDefault();
			$('<div id="holychatwindow"><div id="chatlist"></div><div id="chatsend"></div></div>').appendTo('body').show('slow');
			
			$('#chatlist').load('/chats/xhr_view/');
			$('#chatsend').load('/chats/xhr_send/');
									  
		});
		
		$('#collection .intro-regular:last').removeClass('intro-regular').addClass('intro-last');
		
		validateForms();
		$('a#toLoginPage').click(function(event){
			event.preventDefault();
			
			if( $('#loginFormSmall').hasClass('open')  )
			{
				$('#loginFormSmall').hide();
				$(this).parent('li').removeClass('active');
				$('#loginFormSmall').removeClass('open');
			}
			else
			{
				$('#loginFormSmall').show();
				$('#loginFormSmall').addClass('open');
				$(this).parent('li').addClass('active');
			}
		
		});
		
		
		$('#loginFormSmall h3').click(function(){
			
			if( $('#loginFormSmall').hasClass('open')  )
			{
				$('#loginFormSmall').hide();
				$(this).parent('li').removeClass('active');
				$('#loginFormSmall').removeClass('open');
			}
			else
			{
				$('#loginFormSmall').show();
				$('#loginFormSmall').addClass('open');
				$(this).parent('li').addClass('active');
			}
		
		});
		
		
		$('#switch-language ul').hide();
		
		$('#switch-language a.switch-language').click(function(event){
			event.preventDefault();
		});
		
		$('#switch-language').hover(
		
		function(){
				$('#switch-language ul').show('fast');
		},
		function(){
				$('#switch-language ul').hide();
		}
		);
		
		// var domEl = $(this).get(0);

		$('#embedHolyClip').click(function(){
		var domEl = $(this).get(0);
		domEl.focus();
		domEl.select();
		});
		
		
		$('#urlHolyClip').click(function(){
		var domEl = $(this).get(0);
		domEl.focus();
		domEl.select();
		});
				
		/* tabs for toplists*/
		$('#home-list-clips ul:not(:first)').hide();	
		$('#home-jump-clips li:first').addClass('active');	
		$('#home-jump-clips li a').click(function(event){
			event.preventDefault();
			var divid = $(this).attr('href');
			$('#home-list-clips ul').hide();
			$('#home-jump-clips li').removeClass('active');
			$(this).parent('li').addClass('active');
			$(divid).show();
		});

		/* same thing for the clip page actions */
		$('#clip-actions .cnt > ul:not(:first)').hide();	
		$('#clip-jump-actions li:first').addClass('active');	
		$('#clip-jump-actions li a').click(function(event){
			event.preventDefault();
			var divid = $(this).attr('href');
			$('#clip-actions .cnt > ul').hide();
			$('#clip-jump-actions li').removeClass('active');
			$(this).parent('li').addClass('active');
			$(divid).show();
		});		

		$('#loginFormSmall').prepend('<div class="top"></div>');
		$('.info-pod').append('<div class="btm"></div>');
		$('.info-pod').prepend('<div class="top"></div>');
		
		$('ul.clips-index li').hover(									 
			function(){$(this).addClass('hover')},
			function(){$(this).removeClass('hover')}		
		);
		
		/*
		cant do this there are profuile links in the li as wel. 
		$('ul.clips-index li').click(function(){
			// first anchor
			var link = $(this).find('a').eq(0).attr('href');
			document.location = link;
		});
		*/


		/*
		Radio, checkbox, select replacements ============================
		*/
		$("form").jqTransform();


		/*
		Submitbuttons stylen ============================
		*/
		$("form").stylesubmitbuttons();

		/*
		Filefield replacements ============================
		*/
		
		$("#UserPhoto").filestyle({ 
			 image: "/images/browse.png",
			 imageheight : 21,
			 imagewidth : 79,
			 width : 120
		 });

		
		// same for the pijlers
		$('#pijlers-layout .pijlers-2 .cms-text').addClass('pijler');
		$('#pijlers-layout .pijlers-3 .cms-text').addClass('pijler');
		$('#pijlers-layout .pijlers-4 .cms-text').addClass('pijler');
		$('#pijlers-layout div.pijler').fauxColumnHeights(3);
		
		//$('#pijlers-layout div.pijler').hovermouseover(function());
		$('#pijlers-layout .pijlers-1').addClass('interactive-pod');
		$('#pijlers-layout .pijlers-2').addClass('interactive-pijler');
		$('#pijlers-layout .pijlers-3').addClass('interactive-pijler');
		$('#pijlers-layout .pijlers-4').addClass('interactive-pijler');
		
		$('#pijlers-layout .interactive-pijler .cms-text').fauxColumnHeights(3);
		
		$(".pijlers-1").hover(
		  function(){
			  $('.pijlerpijl').addClass('pijlerpijl-active');
			  },
		  function(){
			  $('.pijlerpijl').removeClass('pijlerpijl-active');
			  }
		);
		
		$('ul.clips-index li').fauxColumnHeights(3);
		
		$('#homepages-display #searchbar fieldset div input.text').each(function()
		{
				if( $(this).val() == '' )
				{
				var labeltekst = $(this).parent().find('label').html();
				$(this).val(labeltekst);
				}
		}
		);
		
		$('#homepages-display #searchbar fieldset div input.text').focus(function()
		{
			var labeltekst = $(this).parent().find('label').html();
			if( $(this).val() ==  labeltekst )
			{
				$(this).val('');	
			}
			
		});


		$('#show-do-rating span.textversion').hide();
		$('#show-do-rating span.star').mouseover(function()
		{
			if( $('#holyusername').length > 0 )
			{
				$('span#help-voting').show();
			}
			else
			{
				$('#submit-vote-warning').show();
			}
			$('#show-do-rating').addClass('busyvoting');
			
			var cvote = $(this).attr('id').replace('rating-','');
				
			$('#show-do-rating span.star').each(function()
				{
					var vote = $(this).attr('id').replace('rating-','');
					if ( parseInt(vote) <= cvote)
					{
					$(this).addClass('active');						
					}
					else
					{
					$(this).removeClass('active');						
					}
			});
		});

		$('#show-do-rating').mouseout(function()
		{
			$('#show-do-rating').removeClass('busyvoting');
			$('#show-do-rating span.star').removeClass('active');
			//$('#submit-vote-warning').hide();
			//$('span#help-voting').hide();
		});
		
		$('#show-do-rating span.star').click(function()
		{
			if( $('#holyusername').length > 0 )
			{
				var cclip = $('a#testholyplayer').attr('rel');
				var cvote = $(this).attr('id').replace('rating-','');
				//alert( $(this).attr('id') );
				//alert( cvote );
				var voteurl = '/ratings/xhrvote/'+cclip+'/'+cvote;
				//alert (voteurl);
				$('span#help-voting').load(voteurl);
				$('span#help-voting').show();
				$('#show-do-rating span.star').each(function()
				{
					var vote = $(this).attr('id').replace('rating-','');
					if ( parseInt(vote) <= cvote)
					{
						$(this).addClass('star-on');						
						$(this).removeClass('star-off');						
					}
					else
					{
						$(this).removeClass('star-on');
						$(this).addClass('star-off');						
					}
				});
			}
			else
			{
				$('span#submit-vote-warning').show();
				$('span#help-voting').hide();
			}
		});


		$('#submit_favorite').click(function(event){	
											 
				if( $('#holyusername').length > 0 )
				{
					// do ajax
					event.preventDefault();
					var clipid = $('#FavoriteClipId').val();
					$('ul#add-to-favorites > li > div').load('/favorites/xhradd/'+clipid);
				}
				else
				{
					$('#submit_favorite_warning').show();
					$('#submit-favorite-box').hide();
					return false;
				}
		});
		
		
		$('#submit-comments-box').click(function(){	
											 
				if( $('#holyusername').length > 0 )
				{
					// do ajax
					//var clipid = $('#CommentClipId').val();
					//$(this).load('/comments/add/'+clipid);
					
				}
				else
				{
					$('#submit-comments-warning').show();
					$('#submit-comments-box').hide();
				}
		});
		
		if ( $('#submit-comments-box').length > 0 ) 
		{
			
			$.getScript("/js/jqtinymce/jscripts/tiny_mce/jquery.tinymce.js", function(){
				
			$('#submit-comments-box textarea').tinymce({
					// Location of TinyMCE script
					script_url : "/js/jqtinymce/jscripts/tiny_mce/tiny_mce.js",
					// General options
					theme : "advanced",
					plugins : "safari",		
					// Theme options
					theme_advanced_buttons1 : "bold,italic,underline,charmap",
					theme_advanced_buttons2 : "",
					theme_advanced_buttons3 : "",
					theme_advanced_buttons4 : "",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "none",
					theme_advanced_resizing : false,
					content_css : "/css/mce.css",
					editor_css : "/css/mce.css"

				});


			});
		}
		
		/* get report form for reviewers */
		if ( $('#clips-view #user-reviewer').length > 0 ) 
		{
			var current_community_slug = $('#current_community_slug').html();
			var current_language_code = $('#current_language_code').html();	
			var clipid = $('a#testholyplayer').attr('rel');
			$('<div id="reviewerfunctions"></div>').appendTo('#main-content');
			$('#reviewerfunctions').load('/'+current_community_slug+'/'+current_language_code+'/reports/add/'+clipid);
		}
		
		
		/* get report form for workshopleiders */
		if ( $('#clips-view #user-workshopleider').length > 0 ) 
		{
			var current_community_slug = $('#current_community_slug').html();
			var current_language_code = $('#current_language_code').html();	
			var clipid = $('a#testholyplayer').attr('rel');
			$('<div id="workshopleidersmenu"></div>').appendTo('#main-content');
			$('#workshopleidersmenu').load('/'+current_community_slug+'/'+current_language_code+'/clips/workshopleidertools/'+clipid);
		}
		
		
		
		/*
		==================================================================
		REPLYS SLIDER
		*/		
		if( $('#reply-list li.clip-reply').length > 3 )
		{
				$('#reply-list').prepend('<span class="viewer-navigate-button navprev"><span>previous</span></span>');
				$('#reply-list').append('<span class="viewer-navigate-button navnext"><span>next</span></span>');
				
				$('#reply-list li.clip-reply:lt(3)').addClass('visible').show();
				$('#reply-list li.clip-reply:gt(2)').addClass('hidden').hide();
				
				$('#reply-list .navprev').click(function(){
					// first one hidden
					var firstvisible = $('#reply-list li.visible:first');
					var indexed = $('#reply-list li').index(firstvisible);
					var firstvisibleindex = parseInt(indexed) - 1;
					var lastvisibleindex = firstvisibleindex + 2;
					if(firstvisibleindex < 0)
					{
						return false;
					}
					$('#reply-list li.clip-reply:eq('+firstvisibleindex+')').removeClass('hidden').addClass('visible').show();
					$('#reply-list li.clip-reply:gt('+lastvisibleindex+')').removeClass('visible').addClass('hidden').hide();
																			
				});
				
				$('#reply-list .navnext').click(function(){
					var firstvisible = $('#reply-list li.visible:first');
					var indexed = $('#reply-list li').index(firstvisible);
					var firstvisibleindex = parseInt(indexed) + 1;
					var lastvisibleindex = firstvisibleindex + 2;
					var lastposindex = $('#reply-list li').length - 1;
					if(lastvisibleindex > lastposindex  )
					{
						return false;
					}
					$('#reply-list li.clip-reply:lt('+firstvisibleindex+')').removeClass('visible').addClass('hidden').hide();
					$('#reply-list li.clip-reply:eq('+lastvisibleindex+')').removeClass('hidden').addClass('visible').show();
				});
		}

		/*
		==================================================================
		SLIDER
		*/
		
		$('div.viewer-block').each(function(){
			$('<div class="viewer-focus"><h3></h3><div class="viewbig"></div></div>').prependTo(this);
			$(this).find('a.viewer-thumb').wrapAll('<div class="tn-nav"></div>');
		});
		
		
		$('div.tn-nav').each(function()
		{
			if( $(this).find('a.viewer-thumb').length > 4 )
			{
				$(this).find('a.viewer-thumb:gt(3)').addClass('hidden');
				$(this).prepend('<span class="viewer-navigate-button navprev"><span>previous</span></span>');
				$(this).append('<span class="viewer-navigate-button navnext"><span>next</span></span>');
			}
		});
		
		$('div.tn-nav .viewer-navigate-button').click(function()
		{
			if( $(this).hasClass('navnext'))
			{
				$('div.viewer-block a.tn_next').click();
			}
			else
			{
				$('div.viewer-block a.tn_prev').click();
			}

		});
		
		$('div.tn-nav a.viewer-thumb').click(function(event){
			
			event.preventDefault();
			
			if ( $(this).hasClass('hidden') )
			{
				// show this one, hide nr -3
				$(this).removeClass('hidden');
				if ( $(this).hasClass('tn_next') )
				{
					var indexhide = $("div.tn-nav a.viewer-thumb").index(this);
					indexhide = parseInt(indexhide) - 3;
					$('div.viewer-block .tn-nav a.viewer-thumb:lt('+indexhide+')').addClass('hidden');
				}
				else if ( $(this).hasClass('tn_prev') )
				{
					var indexhide = $("div.tn-nav a.viewer-thumb").index(this);
					indexhide = parseInt(indexhide) + 3;
					$('div.viewer-block .tn-nav a.viewer-thumb:gt('+indexhide+')').addClass('hidden');
				}
			}

			
			$('div.viewer-block a.viewer-thumb').removeClass('tn_current');
			$('div.viewer-block a.viewer-thumb').removeClass('tn_next');
			$('div.viewer-block a.viewer-thumb').removeClass('tn_prev');
			$(this).addClass('tn_current');
			$(this).next('a.viewer-thumb').addClass('tn_next');
			$(this).prev('a.viewer-thumb').addClass('tn_prev');
			var ctitle = $(this).attr('title');
			//.toUpperCase()
			var href = $(this).attr('href');
			// the parent is the viewer-block
			var viewbig = $(this).parents('.viewer-block').find('.viewbig');
			var header = $(this).parents('.viewer-block').find('h3:first');
			header.html(ctitle);
			viewbig.html('');
			
			if( href.indexOf('holyPlayer') != -1 )
			{
				viewbig.css({height:'430px'});
				//alert('hplayer');
				// get the data for the hplayer
				var nomineeblock = $(this).attr('id').replace('nom-','nominee-');
				//alert(nomineeblock);
				$('.nominee').hide();
				$('#'+nomineeblock).show();
				
				$(this).flash(
        			{ width: 511, height:430, id:'embedholyplayer'},
					{ version: 8 },
						function(htmlOptions) 
						{
							$this = $(this);
							var next_clip_url = $('#'+nomineeblock + ' .next_clip_url').html();
							var respond_url = $('#'+nomineeblock + ' .clip_respond_url').html();
							
							htmlOptions.src = $this.attr('href');
							htmlOptions.wmode = 'opaque';
							htmlOptions.flashvars = 
							{ 
							clip_id: $('#'+nomineeblock + ' .clip_id').html(),
							autoplay: '1',
							repeat: '0',
							embedplayer : '1',
							mute : '0',
							next_url : next_clip_url,
							react_url : respond_url
							}
							//alert(viewbig);
							$(viewbig).append($.fn.flash.transform(htmlOptions));
						}

					);
				
			}
			else if( href.indexOf('.flv') == -1 )
			{
				st = 'width:495px; height:330px; background:#FFF url('+href+')';
				var rimage = $('<span class="imgwrap" style="'+st+'"></span>');
				rimage.fadeOut().appendTo(viewbig).fadeIn('slow');
			}
			else
			{
				var fmovie = $('<object width="495" height="330" name="player" id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="/flvplayer/jw51/player.swf" name="movie"/><param value="true" name="allowfullscreen"><param value="always" name="allowscriptaccess"><param value="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50" name="flashvars"><embed name="player1" id="player2" width="495" height="330" allowfullscreen="true" allowscriptaccess="always"  type="application/x-shockwave-flash" src="/flvplayer/jw51/player.swf" flashvars="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50"/></object>');
				fmovie.appendTo(viewbig);
			}
			
			if( $('.tn-nav a').length < 2  )
			{
				 $('.tn-nav').hide();	
			}
			
		});
		
		
		
		
		
		/*
		==================================================================
		ALBUM viewer / SLIDER
		*/
		
		/* give the albums some thumbnails */
		$('li.album').each(function(){
			$(this).find('a.viewer-thumb:first').clone().appendTo(this).addClass('albumthumb');
		});
		
		$('a.albumthumb').click(function(event){
			event.preventDefault();
			$(this).parent('li.album').click();
		});
		
		
		$('li.album').click(function(){
			
			$('li.album').removeClass('active');
			$(this).addClass('active');
			
			var albumtitle = $('h3', this).html();
			var maintext = $('.main-text', this).html();
			//alert(maintext);
			$('#current-album-text').html(maintext);
			$('#signposts-currentalbum .album-title').html(albumtitle);
			
									 
			$('#alb-tn-navnav').html('<ul></ul>');
			$('#album-tn-nav').html('<div class="ab-nav" id="navvideos"></div><div class="ab-nav" id="navfotos"></div>');
			$('.ab-nav').hide();
			if($(this).find('ul.album-videos').length > 0)
			{
				$('<li id="setvideo"><a href="#video"><span>Video\'s</span></a></li>').appendTo('#alb-tn-navnav ul');
				$(this).find('ul.album-videos').clone().appendTo('#navvideos');
				$('#signposts-currentalbum .total-videos').html( $(this).find('ul.album-videos li').length );
							
			}
			if($(this).find('ul.album-fotos').length > 0)
			{
				$('<li id="setfoto"><a href="#fotos"><span>Foto\'s</span></a></li>').appendTo('#alb-tn-navnav ul');
				$(this).find('ul.album-fotos').clone().appendTo('#navfotos');
				$('#signposts-currentalbum .total-fotos').html( $(this).find('ul.album-fotos li').length );
			}
			
			$('#alb-tn-navnav ul li').click(function()
			{
				if( $(this).hasClass('active') )
				{
					return;
				}
				
				$('#alb-tn-navnav ul li').removeClass('active');
				$(this).addClass('active');
				
				if($(this).attr('id') == 'setvideo')
				{
					$('#navvideos').show().perSlider();
					$('#navfotos').hide();
					$('#signposts-currentalbum .total-fotos').hide();
					$('#signposts-currentalbum .total-videos').show();
					$('#signposts-currentalbum .viewtype').html('video');
				}
				else
				{
					$('#navvideos').hide();
					$('#navfotos').show().perSlider();
					$('#signposts-currentalbum .total-videos').hide();
					$('#signposts-currentalbum .total-fotos').show();
					$('#signposts-currentalbum .viewtype').html('foto');
				}
				
			});
			
			$('#alb-tn-navnav ul li:first').click();

		});
		
		$('li.album:first').click();
		

		
		
		/*
		
		$('<object width="495" height="300" name="player" id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="/flvplayer/jw51/player.swf" name="movie"/><param value="true" name="allowfullscreen"><param value="always" name="allowscriptaccess"><param value="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50" name="flashvars"><embed name="player1" id="player2" width="495" height="300" allowfullscreen="true" allowscriptaccess="always"  type="application/x-shockwave-flash" src="/flvplayer/jw51/player.swf" flashvars="file=' + href + '&amp;autostart=1&amp;screencolor=white&amp;repeat=always&amp;volume=50"/></object>').insertBefore(this);
		
		*/
		
		//$('#clip-scroller').css('height', '244px');
		//$('#clip-scroller').css('overflow', 'hidden');
		
		
		$('#newsletter form').each( function(){
		
			var labeltxt = $(this).find('label:first').html();
			$(this).find('#NewslettersubscriptionEmail').val(labeltxt);
			$(this).find('label:first').hide();								 
		});
		
		
		$('#pijlers-layout .pod').each( function(){
		
			if( $(this).hasClass('pijlers-2') || $(this).hasClass('pijlers-3') || $(this).hasClass('pijlers-4') )
			{
				$(this).prepend('<span class="pijlerpijl"></span>');	
			}
		
		});
		
	/*	
		$('#ClipCliplistingfilter').change(function(){
			
			var newfilter = $(this).val();
			//alert(newfilter);
			
			if(newfilter == 'showspiral')
			{
				var url = document.location.toString();
				//alert(url);
				var newurl = url.replace('grouplist','spiral');
				document.location.replace(newurl);	
			}
			else
			{
				var url = document.location.toString();
	
				//alert(url);
				var newurl = url.replace('cliplistingfilter:','');
				newurl = newurl.replace('allclips','');
				newurl = newurl.replace('commshow','');
				newurl = newurl+'/cliplistingfilter'+':'+newfilter+'/';
				//newurl = newurl.replace('//','/');
				//alert('next='+newurl);
				document.location.replace(newurl);
			}
			
		});
	*/	

		$('#home-list-clips ul li:not(.clips-in-the-future)').click(function(){
		   var url = $(this).find('a').attr('href');
		   if(url != 'undefined')
		   {
		   	document.location.href=url;
		   }
		});
		
		$('.linksentirely').click(function(){
		   var url = $(this).find('a').attr('href');
		   document.location.href=url;
		});
		
		$('.interactive-pijler').click(function(){
		   var url = $(this).find('a').attr('href');
		   document.location.href=url;
		});
		
		$('.interactive-pod').click(function(){
		   var url = $(this).find('a').attr('href');
		   document.location.href=url;
		});
		
		
		$('#sub-content #group-related').each(function(){
			
			var paging = $('#current_group_paging').html();
			
			var url = $(this).find('a').attr('href').replace('grouplist','xhrgrouprelatedshortlist/page:'+paging);
			//alert(url);
			$.get(url, function(data){
  			//alert("Data Loaded: " + data);
				$('#group-short-list').html(data);
				initXhrPaging();
				// make sure that an active clip is scrolled somewhat up in the box
				var clipid = $('#testholyplayer').attr('rel');
				
				$('#group-short-list li div.relatedclip_'+clipid ).each(function(){
					//alert('group-short-list li.relatedclip_'+clipid);
					//$(this).css({'padding' : ''});
					$(this).addClass('active-clip-list-item');
					// make sure its visible as well.
					var offsetparent = $('#group-short-list').offset();
					var offsetlistitem = $(this).offset();
					var difference =  offsetlistitem.top - offsetparent.top - 83;
					//alert (difference);
					$('#group-short-list ul').scrollTop(difference);
				});
				
			});
			
		}); 
		
		$('#sub-content #mystic-related').each(function(){
			var url = $(this).find('a').attr('href').replace('relatedlist','xhrmysticrelatedshortlist');
			//alert(url);
			$.get(url, function(data){
  			//alert("Data Loaded: " + data);
				$('#mystic-short-list').html(data);
				initXhrPaging();
			});
			
		}); 
		
		$('#sub-content #user-related').each(function(){
			var url = $(this).find('a').attr('href').replace('userclips','xhruserrelatedshortlist');
			//alert(url);
			$.get(url, function(data){
  			//alert("Data Loaded: " + data);
				$('#user-short-list').html(data);
				initXhrPaging();
			});
			
		}); 
		
		$('#sub-content #user-mine').each(function(){
			var url = $(this).find('a').attr('href').replace('myclips','xhrminerelatedshortlist');
			//alert(url);
			$.get(url, function(data){
  			//alert("Data Loaded: " + data);
				$('#user-short-list').html(data);
				initXhrPaging();
			});
			
		}); 
		
		$('#sub-content #user-favorites').each(function(){
			var url = $(this).find('a').attr('href').replace('userfavorites','xhruserfavoriteshortlist');
			//alert(url);
			$.get(url, function(data){
  			//alert("Data Loaded: " + data);
				$('#userfavorites-short-list').html(data);
				initXhrPaging();
			});
			
		}); 
		
		$('#sub-content a#myfavlist').each(function(){
			var url = $('a#myfavlist').attr('href').replace('myfavorites','xhrmyfavoriteshortlist');
			//alert(url);
			$.get(url, function(data){
  			//alert("Data Loaded: " + data);
				$('#myfavorites-short-list').html(data);
				initXhrPaging();
			});
			
		}); 
		
		
		
		initXhrPaging();		
		
		$('.info-pod').each(function(){
			if( $(this).hasClass('linksentirely') )
			{
				$(this).append('<span class="arrow"></span>');	 
			}
		});
		

		
		
		$('div.user-form div.radio fieldset').each(function(){										  
			var labeltext = $(this).find('legend').html();
			$('<label class="legend">'+labeltext+'</label>').insertBefore(this);
		});
		
		$('#UserUsername').blur(function(){
			$('#usernamehelp span.message').html('...');
			
			var username = $(this).val();
			 //alert(username);
			if(username != '')
			{
				var url = '/users/xhr_check_username/'+username;

				$.get( url , function(data)
				{
					if (data.indexOf('OK') > 1)
					{
					}
					else
					{
						$('#usernamehelp').show();
						$('#usernamehelp span.message').html(data);
						
						$('a.tip').click(function(event)
						{
							event.preventDefault();
							var tip = $(this).html();
							$('#UserUsername').val(tip);
							$('#usernamehelp').hide();
						});
					}
	
				});
			
			}
			 
		});
		
		$('#CformOtherinterest').parent('div').find('label').addClass('interestlabel').hide();
		
		$('form.jqtransformdone .radio-option').click(function()
		{		
			//alert('hi');
			$('#CformInterestAnders').each(function(){
				if( (this.checked) )
				{
					$('.interestlabel').show();
					$('#CformOtherinterest').show();
					
				}
				else
				{
					$('.interestlabel').hide();
					$('#CformOtherinterest').hide();				
				}
			});
		});
		
		
		
	});
	/*
	====================================================================================
	end onload DOM 
	====================================================================================
	*/
	
	
	/*
	====================================================================================
	some functions called
	====================================================================================
	*/
	
	function nextNominee(nominee_id)
	{
		//alert(nominee_id);
		//$('div.tn-nav a.viewer-thumb')
		$("#nom-"+nominee_id).next("a.viewer-thumb").click();
	}
	
	function nowPlaying(clipid)
	{
		//alert(clipid);
		if( $('#cardata span#car_clip_'+clipid).length > 0 )
		{
			var titellink = $('#cardata span#car_clip_'+clipid+' .clip_link').html();
			$('#hpclipcontainer .clip-details h2').html(titellink);
			var authorlink = $('#cardata span#car_clip_'+clipid+' .author_link').html();
			$('#hpclipcontainer .clip-details span.author').html(authorlink);
		}
	}
	
	$(window).load(function(){
		setHolyPlayerContainerToInlinePosition()
	});
	
	
	function setHolyPlayerContainerToInlinePosition()
	{
						
		if($('#testholyplayer').length > 0)
		{
			var offset = $('#testholyplayer').offset();
			
			
			// klaarblijkelijk is offset niet cross browser. constatering, geen fix.
			
			if (/Chrome/.test (navigator.userAgent))
			{
				offset = $('#view-clip').offset();
				
				//alert('chrome offset view-clip 4');
				//alert(offset.top);
				//alert(offset.left);
				var newtop = Number(offset.top)+45;	
				var newleft = Number(offset.left) + 27;
				
			}
			else if (/Opera/.test (navigator.userAgent))
			{
				var newtop = Number(offset.top)+10;	
				var newleft = parseInt(offset.left);
			}
			else if (/MSIE/.test (navigator.userAgent))
			{
				//alert(navigator.userAgent);
				var newtop = Number(offset.top)+10;	
				//var newtop = 300;	
				var newleft = parseInt(offset.left);
				
			}
			else
			{
				var newtop = Number(offset.top);
				var newleft = Number(offset.left);
			}
			
			// keep it to round pixels please
			newtop = parseInt(newtop);
			newleft = parseInt(newleft);
			
			
			$('#holyPlayerContainer').css({position:'absolute','z-index':300,left: newleft+'px', top: newtop+'px'});
		
		}
	}


	function fullScreen(status)
	{

		if(status == 1)
		{
			var wheight = $(window).height();
			var wwidth = $(window).width();
			$('#holyPlayerContainer').css({left: 0,top: 0,'z-index':1300});
			$('#theholyplayer').attr({'width':wwidth,'height':wheight}).width(wwidth).height(wheight);
			$(window).scrollTop(0);		
		}
		else
		{
			$('#theholyplayer').attr({'width':502,'height':415}).width(502).height(415);
			setHolyPlayerContainerToInlinePosition();
		}
	}


	function clip_content_alert()
	{
		$.openDOMWindow({ 
					height:450,  
					width:350,
					windowPadding:0,  
					windowBGColor:'transparent',  
					borderSize:'0', 
					windowSourceID: '#holyDomWindow',
					overlayOpacity:50 
		});	
		var clipid = $('#testholyplayer').attr('rel');
		var lang = $('#current_language_code').html();
		//var dom = $('#current_domain').html();
		$('#holyDomWindowContent').load('/holy/'+lang+'/clipwarnings/xhrform/'+clipid, function()
			{
				$("#ClipwarningAddForm #ClipwarningReasonInsultingOrOffensive").click();
				$("#clipwarning").jqTransform();
				$("#clipwarning").stylesubmitbuttons();
				$("#ClipwarningAddForm").get(0).onsubmit = validate;
			}
		);
	}
	
	
	function initXhrPaging()
	{
		$('#clips-grouplist .paging a').click(function(event){
			event.preventDefault();
			// pin height
			var sh = $('#searchres .clips-index').height()+'px';
			$('#searchres .clips-index').css('height',sh).html('').addClass('waiting');
			var url = $(this).attr('href').replace('grouplist', 'xhrgrlist');
			url = url.replace('search', 'xhrsrch');
			url = url.replace('userclips', 'xhruclips');
			//alert(url);
			$.get(url, function(data){
  			//alert("Data Loaded: " + data);
			$('#searchres').html(data);
			$('ul.clips-index li').fauxColumnHeights(3);
			initXhrPaging();
			});
		});
		
		
		$('#sub-content #group-related .paging a').click(function(event){
			event.preventDefault();			
			var url = $(this).attr('href');
			$('#group-short-list ul').html('').addClass('waiting');
			//alert(url);
			$.get(url, function(data){
			$('#group-short-list').html(data);
			initXhrPaging();
			});
		});
		
		$('#sub-content #mystic-related .paging a').click(function(event){
			event.preventDefault();			
			var url = $(this).attr('href');
			$('#mystic-short-list ul').html('').addClass('waiting');
			//alert(url);
			$.get(url, function(data){
			$('#mystic-short-list').html(data);
			initXhrPaging();
			});
		});
		
		$('#sub-content #user-related .paging a').click(function(event){
			event.preventDefault();			
			var url = $(this).attr('href');
			$('#user-short-list ul').html('').addClass('waiting');
			//alert(url);
			$.get(url, function(data){
			$('#user-short-list').html(data);
			initXhrPaging();
			});
		});
		
		$('#sub-content #user-mine .paging a').click(function(event){
			event.preventDefault();			
			var url = $(this).attr('href');
			$('#user-short-list ul').html('').addClass('waiting');
			//alert(url);
			$.get(url, function(data){
			$('#user-short-list').html(data);
			initXhrPaging();
			});
		});
		
		$('#sub-content #user-favorites .paging a').click(function(event){
			event.preventDefault();			
			var url = $(this).attr('href');
			$('#userfavorites-short-list ul').html('').addClass('waiting');
			//alert(url);
			$.get(url, function(data){
			$('#userfavorites-short-list').html(data);
			initXhrPaging();
			});
		});

		$('#sub-content #my-favorites .paging a').click(function(event){
			event.preventDefault();			
			var url = $(this).attr('href');
			$('#myfavorites-short-list ul').html('').addClass('waiting');
			//alert(url);
			$.get(url, function(data){
			$('#myfavorites-short-list').html(data);
			initXhrPaging();
			});
		});
		
	}
	

	
	/*
	====================================================================================
	start onload WINDOW 
	====================================================================================
	*/
	
	$(window).load(function()
	{

		$(".cms-text img").each(function(){
												 
				if( $(this).hasClass('noborder') )
				{
				return;	
				}
				var st = $(this).attr('style');	
				var cn = $(this).attr('class');	
				var imgsrc = $(this).attr('src');	
				var w = $(this).attr('width');	
				var h = $(this).attr('height');	
				$(this).attr('style', '');	
				st += '; width:'+w+'px; height:'+h+'px; background:url('+imgsrc+')';
				$(this).wrap('<span class="imgwrap '+cn+'" style="'+st+'"></span>');
				$(this).hide();
		});

		
		$("#userview img").each(function(){
				var st = $(this).attr('style');	
				var imgsrc = $(this).attr('src');	
				var w = $(this).attr('width');	
				var h = $(this).attr('height');	
				$(this).attr('style', '');	
				st += '; width:'+w+'px; height:'+h+'px; background:url('+imgsrc+')';
				$(this).wrap('<span class="imgwrap" style="'+st+'"></span>');
				$(this).hide();
		});
		
		$("#clip-details .user-details img").each(function(){
				var st = $(this).attr('style');	
				var imgsrc = $(this).attr('src');	
				var w = $(this).attr('width');	
				var h = $(this).attr('height');	
				$(this).attr('style', '');	
				st += '; width:'+w+'px; height:'+h+'px; background:url('+imgsrc+')';
				$(this).wrap('<span class="imgwrap" style="'+st+'"></span>');
				$(this).hide();
		});
		
		$('.fch').fauxColumnHeights(2);
		
		$('#collectioncollage img').each(function(){			

			var bgpos = 0;
			var bgsrc = $(this).attr('src');
			
			$('#sub-content div.navigation-item').each( function()
			{
				if( ! $(this).hasClass('contactform') )
				{
					$(this).css('background-image','url('+ bgsrc +')').css('background-position','center '+ bgpos+'px');
					bgpos -= 47;
				}
			});
			
		});

		$(".interactive-pijler img").each(function(){
				var st = $(this).attr('style');	
				var cn = $(this).attr('class');	
				var imgsrc = $(this).attr('src');	
				var w = $(this).attr('width');	
				var h = $(this).attr('height');	
				$(this).attr('style', '');	
				st += '; width:'+w+'px; height:'+h+'px; background:url('+imgsrc+') 0 0;';
				$(this).wrap('<div class="imgwrapborder"><span class="imgwrap '+cn+'" style="'+st+'"></span></div>');
				$(this).hide();
		});
		
		
		//cvvvideoverslag
		if(document.location.hash)
		{
			var el = String(document.location.hash);
			//alert(el);
			if( $(el).hasClass('viewer-thumb') )
			{
				$(el).addClass('tn_next');
				$(el).click();
				document.location.hash = '#top';
			}
		}
		else
		{
			$('div.viewer-block a.viewer-thumb:first').click();	
		}
		
		
		
		$('span.clearcacheforclip').each(function(){
		
			var clipid = $(this).html();
			$(this).load('/clips/xhr_clearcacheforclip/'+clipid);
												  
		});
		
		
		
	});
	
/*
====================================================================================
end onload WINDOW 
====================================================================================
*/
	
/* ============================================================================ */

