var basehref = $('base').attr('href');

var fancySettings = {
	'hideOnContentClick': true,
	'cyclic'		:	true,
	'margin'		:	20,
	'centerOnScroll':	true,
	'overlayOpacity':	0.8,
	'overlayColor'	:	'#b4b0af',
	'speedIn'		:	600, 
	'speedOut'		:	200, 
	'overlayShow'	:	true,
	
	'titleShow'		: false,		// Toggle title
	'titlePosition'	: 'over'	// The position of title. Can be set to 'outside', 'inside' or 'over'

}

var loaded = [];
var inited = [];
var deeplinked;

var numClass = function(count){
	//return count >= 10 ? 'double' : 'single';
}
	
// init & start
$(function() {
	
	// init scrollto();
	initscrollto();
	
	// menu hover style
	$('#header > ul > li > ul').hover(function(){
		$(this).parent().addClass('hover');
	},function(){
		$(this).parent().removeClass('hover');
	});
	
});

function initpage(parent){
	
	var id = $(parent).attr('id');
	
	if(id ){
		
		if(jQuery.inArray(id,inited) >= 0){
		
		} else {
			
			wc('init page: ' + id);
			
			// fancybox
			$('a.enlarge',parent).fancybox(fancySettings);
			
			// scroll content
			contentWrapScroll(parent);
			
			// gallery cycle
			addCycle( $('.contentholder .folder.topimages.image',parent),false,true);
			
			// enlarge icon in image
			$('a.enlarge.wide').prepend( $('<img/>').attr('src',basehref+'gui/icons/enlarge.png').addClass('enlargeicon') );
			
			// readmore ajax
			initreadmoreless(parent);
			
			// forms ajax
			initAjaxForm(parent);
			
			
			// register as inited
			inited.push(id);
		}
			
	}
}

function initAjaxForm(parent){

	$('#formholder',$(parent)).parent().scrollTop( 0 );
	
    // bind to the form's submit event 
    $('form',$(parent)).submit(function() { 

        $(this).ajaxSubmit({ 
			target:        false,   // target element(s) to be updated with server response 
			success:       showResponse  // post-submit callback 
		}); 
 
        return false; 
    }); 
    
     // post-submit callback 
	function showResponse(responseText, statusText, xhr, $form)  { 
				
	 	$('#formholder',$(parent)).replaceWith($('#formholder',$(responseText)));
	 	
	 	initAjaxForm(parent);
		
	} 
}

function initreadmoreless(parent){

	if( $('.readless',$(parent)).length ){
		deeplinked = true;
	}
	
	$('.readmore,.readless',$(parent)).each(function(){
	
		var href = $('a:first',$(this)).attr('href');
		var holder = $(this).closest('.listcontent');
		var listitem = holder.parent('div').attr('id');
		var id = $(parent).attr('id');
				
		$(this).click(function(){
			
			if(deeplinked){
				
				$(parent).replaceWith( $('<div id="'+id+'"></div>').load( href + ' .contentholder', function() {
					
					//wc(loaded);
					var idx = inited.indexOf(id); // Find the index
					if(idx!=-1) inited.splice(idx, 1); // Remove it if really found!
					initpage( $('#'+id) );
				}));
				
				deeplinked = false;
			
			} else {
				
				$('h2',$(parent)).hide();
				$('.listcontent',$(parent)).not(holder).parent().hide();
				
				$(holder).load( href + ' h2,p', function() {
						
					initreadmoreless( $('#'+id) );
				});
				
				deeplinked = true;
			}
			
			return false;
		});
	});
}	

function initscrollto(){
		
	// You can modify any default like this
	$.localScroll.defaults.axis = 'xy';
	
	// prep grid
	var grid = $('#header > .sectionsmenu').clone().appendTo( $('<div/>').attr('id','grid').insertBefore( $('#main').hide() ) );
	
	// prep navigationmenu
	$('li > a',$('#header > .sectionsmenu'))
	.click(function(){
		return false;
	})
	.each(function(){
		$(this).attr('href',function(){
			return current_url + '#'+$(this)
			.removeAttr('class')
			.attr('href')
			.replace('.html','')
			.replace(basehref,'')
			.replace('pagina/','')
			.replace('page/','');
		})
	});
	
	//Puts hash in variable, and removes the #(!) character
	var validhash = false;
	if(window.location.hash) {
		var hash = window.location.hash.substring(1).replace('!',''); 
		// hash found
		validhash = (loadedactiveid == hash) ? false : true;
		loadedactiveid = hash;
	}
		
	// load grid	
	$('li > a',grid)
	.removeAttr('class')
	.each(function(){
		
		var href = $(this).attr('href');
			
		var id = $(this)
			//.load( $(this).attr('href') + ' #content' )
			.removeAttr('class')
			//.addClass('content')
			.attr('href')
			.replace('.html','')
			.replace(basehref,'')
			.replace('pagina/','')
			.replace('page/','');
		
		$(this).attr('id',id);
		
		if(validhash && (id == loadedactiveid)) {
			
			// load page without delay and init
			loadAjaxpage(this,id,href,true);
			
			setmenu(id);
					
		} else if(id == loadedactiveid){
		
			// we hebben m al van serverside:
			//wc('using dom: '+id);
			var holder = $('<div id="'+id+'"></div>');
			$(this).replaceWith( holder.html( $('#main > .contentholder') ) );
		
			$(grid).scrollTo( holder,{
				queue:false,
				duration:0,
				onAfter:function( anchor, settings ){
					// The 'this' contains the scrolled element (#content)
					//$(holder);
					initpage(holder);
				}
			});
			
		} else {
		
			// ajax
			// load page with delay
			loadAjaxpage(this,id,href,false,500);
		
		}
		
	});
	
	
	// Scroll initially if there's a hash (#something) in the url 
	// with localscroll
	/*
	$.localScroll.hash({
		target: '#grid', // Could be a selector or a jQuery object too.
		queue:true,
		duration:0,
		onBefore:function( e, anchor, $target ){
			// The 'this' is the settings object, can be modified
			
			var id = $(anchor).attr('id');
			
			if(id != loadedactiveid){
				
				var currentlink = $('a[href$="#'+loadedactiveid+'"]',$('#header > .sectionsmenu'));
				
				var target = $('a[href$="#'+id+'"]',$('#grid'));
				var href = $('a[href$="#'+id+'"]',$('#header > .sectionsmenu')).attr('href');
				
				loadedactiveid = id;
				loadAjaxpage(target,id,href,true);
				beforeload( this,e, anchor, $target );
				
				var clickedlink = $('a[href$="#'+loadedactiveid+'"]',$('#header > .sectionsmenu'));
				var currenttitle = top.document.title;
				var newtitle = currenttitle.replace( currentlink.text(),clickedlink.text() ).replace('page','');
				top.document.title = newtitle;
			}
		}
	});
	*/
	
	
	/**
	 * NOTE: I use $.localScroll instead of $('#navigation').localScroll() so I
	 * also affect the >> and << links. I want every link in the page to scroll.
	 */
	$('#header > .sectionsmenu').localScroll({
		target: '#grid', // could be a selector or a jQuery object too.
		queue:true,
		duration:1000,
		hash:false, // gaat anders niet lekker...
		onBefore:function( e, anchor, $target ){
			// The 'this' is the settings object, can be modified
			
			var currentlink = $('a[href$="#'+loadedactiveid+'"]',$('#header > .sectionsmenu'));
			
			loadedactiveid = $(anchor).attr('id');
			beforeload( this,e, anchor, $target );
			initpage( $('#'+loadedactiveid) );
			
			var clickedlink = $('a[href$="#'+loadedactiveid+'"]',$('#header > .sectionsmenu'));
			
			//if(){
				if (typeof(window.history.pushState) == 'function'){
					window.history.pushState('string',loadedactiveid,clickedlink.attr('href'));
				} else {
					window.location.hash = '#!'+loadedactiveid;
				}
			//}
			
			var currenttitle = top.document.title;
			var newtitle = currenttitle.replace( currentlink.text(),clickedlink.text() ).replace('page','');
			
			top.document.title = newtitle;
			 
		},
		onAfter:function( anchor, settings ){
			// The 'this' contains the scrolled element (#content)
			
			initpage( $('#'+loadedactiveid) );
			
			// track page
			if (typeof _gaq != 'undefined'){
				//_gaq.push(['_trackPageview','/'+controller+'/'+ui.tab.title+'.html']);
				// zorgt voor vertraging... beter een onAfter van maken...
				_gaq.push(
					['_setAccount', account_a],
					['_trackPageview','/'+controller+'/'+loadedactiveid+'.html']
				);
			}
			
		}
	});
	
	function loadAjaxpage(target,id,href,init,timeout){
		
		var timeout = timeout ? timeout : 0;
		
		if(jQuery.inArray(id,loaded) >= 0){
		
		} else {
			
			setTimeout(function() {
				
				wc('load: '+ href);
				
				$(target).replaceWith( $('<div id="'+id+'"></div>').load( href + ' .contentholder', function() {
					
					if( $('#'+id).attr('id') != $('.contentholder:first',$('#'+id)).attr('id').replace('content_','') ){
						$('#'+id).remove();
						$('a[href$="#'+id+'"]',$('#header > .sectionsmenu')).attr('href',function(){
							return $('li:first > a',$(this).next('ul')).attr('href');
						});
					}

					//$('.content',$(this)).removeClass('content');
					$('#grid').scrollTo( $('#'+loadedactiveid) ,{
						queue:false,
						duration:0
					});
					
					if(init){
						initpage( $('#'+id) );
					}
					
					loaded.push(id);
					
				}));
			
			}, timeout);
			
		}
	}
	
	function beforeload( settings, e, anchor, target ){
		
		//settings.axis = 'yx';
		
		var id = $(anchor).attr('id');
		//var clickedlink = $('a[href$="#'+id+'"]',$('#header > .sectionsmenu'));
		
		setmenu(id);
	}
	
	function setmenu(id){
		
		$('li.selected,li.in-path',$('#header > .sectionsmenu')).removeClass('selected').removeClass('in-path');
		$('a[href$="#'+id+'"]',$('#header > .sectionsmenu'))
		.parent('li')
		.addClass('selected')
		.addClass('in-path')
		.parent('ul')
		.parent('li')
		.addClass('selected')
		.addClass('in-path');
	}
}

function contentWrapScroll(parent){
	
	// contentvisibility 
	$('.contentholder',$(parent)).css({'overflow'	: 'visible'});
	// scrollwrap
	$('.contentholder > *:not("a,.folder.image,img")',parent).wrapAll('<span class="scroll"></span>');
}


function loadMovie(elem,autoplay,thumb){
	
	wc('load movie '+ $(elem).attr('id') + (autoplay ? ' autoplay' : ' preview') );
	
	var into =  $('p:first',$(elem));
	
	var dimensions = thumb ? thumb : '600x300';
	var iSeekpoint = '0.1';
	var controlHeight = 0;//18;
	var srcanchor = $('a:first',into);
	var src = $(srcanchor).attr('href');
	
	$('embed',elem).remove();
	$('object',elem).remove();
	$('div:first',elem).remove();
	
	var aDimensions = dimensions.split('x');

	if( $('a:first',into).attr('class') ){
		
		var classes = $('a:first',into).attr('class').split(' ');
		
		for (var i = 0; i < classes.length; i++){
			
			var theSclass = classes[i];
			
			if( !thumb && stristr(theSclass,'dimensions_',true) ){
				
				aDimensions = theSclass.replace('dimensions_','').split('x');
				
				if(!aDimensions[1]){
					aDimensions = dimensions.split('x');
				} 
			} 
			
			if( stristr(theSclass,'seekpoint_',true) ){
				iSeekpoint = theSclass.replace('seekpoint_','');
			} 
			
		}
		
		//wc(aDimensions);
	}
	
	$(into).media({ 
		width:     aDimensions[0], 
		height:    ((aDimensions[1]/1) +controlHeight), 
		autoplay:  autoplay, 
		src:      src,
		bgColor:	'#111111', // background color 
		flashvars:{
			'seekpoint':iSeekpoint,
			'video':src,
			'autoplay':autoplay,
			'autoStart':autoplay
		},
		params:	{
			'z-index':1,
			'wmode':'transparent',
			'controller':false,
			'ShowControls':false,
			'ShowStatusBar':true,
			'ShowDisplay':true,
			'windowlessVideo':true,
			'uiMode':'none',
			'autoStart':autoplay
		},
		attrs:	{
			'scale':'aspect',
			'class':'movie',
			'z-index':1,
			'wmode':'transparent',
			'controller':false,
			'ShowControls':false,
			'ShowStatusBar':true,
			'ShowDisplay':true,
			'windowlessVideo':true,
			'uiMode':'none',
			'autoStart':autoplay
		},
		caption:   false // supress caption text 
	});
	
	$(elem)
	.addClass(function(){
		
		return autoplay ? 'playing' : 'thumb';
	})
	.addClass('vidloaded')
	.prepend( 
		$(srcanchor)
		.parent()
		.css({
			'position':'absolute',
			'left':'-4000px'
		}) 
	);
	
	return false;
}

function loadMovies(elem){
	
	var thumbsize = '120x60';
	
	function showMovie(id,holder,autoplay){
		
		wc('showmovie: '+id);
		
		$('.playing').each(function(){
			
			$(this).removeClass('playing');
			
			//loadMovie($(this),false,thumbsize);
		});
		
		
		$('.video#'+id,$(holder))
		.each(function(){
			
			var hasthumb = $(this).parent('a.moviethumb').length;
			
			if(hasthumb){
				$(this).unwrap();
			}
			
			if(autoplay){
				loadMovie($(this),true);
			} else {
				loadMovie($(this),false);
			}
			
		});
		
		$('.video:not("#'+id+')',$(holder))
		.each(function(){
			
			var id = $(this).attr('id');
			var hasthumb = $(this).parent('a.moviethumb').length;
			
			if(hasthumb){
				
				wc('has thumb: '+id);
				
			} else {
				
				wc('no thumb: '+id);
				
				$(this)
				.wrap(function() {
					return $('<a/>')
					.addClass('moviethumb')
					.mousedown(function(){
						showMovie(id,holder,true);
						return false;
					});
				});
				
				loadMovie($(this),false,thumbsize);
				
				//$('#'+id).parent('a').appendTo(holder);
			}
			//	$(this).parent('a').appendTo(holder);
		});
		
		wc('prepend to holder: '+id);
		$('#'+id).prependTo(holder);
		
		return false;
	}
	
	$('.folder.video.normal').each(function(){
		if( $('.video',$(this)).length > 1 ){
			
			showMovie($('.video:first',$(this)).attr('id'),$(this),false);
			 
		} else {
			
			$(elem,$(this)).each(function(){
				loadMovie( $(this),false);
			});

		}
	});
	
	$(elem).not('.vidloaded').each(function(){
		loadMovie($(this),false);
	});
}

function addCycle(holder,showdescription,pager){
	
	var first = true;
	
	$(holder).each(function(){
		//$(this).html('a');
	});
	
	if( $(holder).length && $('a',holder).length ){
		
		var enlargeH = $('<span/>')
		.addClass('slidenav')
		.addClass('enlargeBtn')
		.append( 
			$('<a/>') 
		).click(function(){
			if( $('a',holder).length > 1 ){
				$(".actslide").trigger('click');
			} else {
				$('a:first',holder).trigger('click');
			}
		});
		
		if( $('a',holder).length > 1 ){
		
			var prevH = $('<span/>')
			.addClass('slidenav')
			.addClass('prevBtn')
			.append( 
				$('<a/>') 
			);
			
			var nextH = $('<span/>')
			.addClass('slidenav')
			.addClass('nextBtn')
			.append( 
				$('<a/>') 
			);
			
			var pauzeH = $('<span/>')
			.addClass('slidenav')
			.addClass('pauzeBtn')
			.append( 
				$('<a/>') 
			)
			.toggle(function() {
				$(holder).cycle('pause'); 
				$(this).addClass('active');
			}, function() {
				$(holder).cycle('resume',true); 
				$(this).removeClass('active');
			});
			
			var title  = $('a:first',holder).attr('title');
			var output = showdescription ? $('<p/>').addClass('description').html(title) : '';
			var pagernav = pager ? $('<div/>').attr('id','slidenav') : '';
			
			$(holder)
			.css({'margin':'0px','padding':'0px','with':'auto'});
			
			var count = $('a',holder).length;
				
			var wrapper = $('<div/>')
			.addClass('easyslideWrapper');
			
			var imgholder = $(holder)
			.addClass('easyslideHolder')
			.wrap( wrapper );
			
			$(imgholder)
			.after(enlargeH)
			.after(nextH)
			.after(pauzeH)
			.after(prevH)
			.after(pagernav)
			.after(output)
			.cycle({ 
				fx:			'fade', 
				pager:		pagernav ? '#slidenav' : false,
				pause:		false,
				pauseOnPagerHover:true,
				delay:		-3500,
				timeout:	5000,
				next:		'.nextBtn', 
				prev:		'.prevBtn',
				after:		onAfter,
				before:		onBefore 
			});
			
			$(holder)
			.parent()
			.hover(
				function(){
					$('.slidenav').fadeIn('300');
				},
				function(){
					$('.slidenav').fadeOut('100');
				}
			);
		
		} else {
			
			$(holder)
			.append(enlargeH);
			
		}
	}
	
	function onBefore() { 
		
		title  = $(this).attr('title');
		
		var prevc = $(this).prevAll('a').length;
		var nextc = (prevc + 2);
		
		prevc = (prevc == 0) ? count : prevc;
		nextc = (nextc > count) ? 1 : nextc;
		
		$('a',prevH)
		.html(Math.abs(prevc))
		.removeClass('double')
		.addClass(function(){
			return numClass(prevc);
		});
		
		$('a',nextH)
		.html(Math.abs(nextc))
		.removeClass('double')
		.addClass(function(){
			return numClass(nextc);
		});
		
		if(!first && showdescription){
		
			output
			.fadeOut('fast',function(){
			
				output
				.html(title) 
				.fadeIn('slow',function(){}); 
				
			});
			
		} else {
		
			$(prevH).addClass('active');
			$(nextH).addClass('active');
			
			first = false;
		}
		
		//$(this).removeClass('actslide');
		$('a',holder).removeClass('actslide');
	} 
	
	function onAfter() { 
	
		$(this).addClass('actslide');
		
	}
	
}

function stristr (haystack, needle, bool) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfxied by: Onno Marsman
    // *     example 1: stristr('Kevin van Zonneveld', 'Van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: stristr('Kevin van Zonneveld', 'VAN', true);
    // *     returns 2: 'Kevin '
    var pos = 0;

    haystack += '';
    pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase());
    if (pos == -1) {
        return false;
    } else {
        if (bool) {
            //return haystack.substr(0, pos);
            return true;
        } else {
            return haystack.slice(pos);
        }
    }
}

function findIndex(array,value){
	var ctr = false;
	for (var i=0; i < array.length; i++) {
		// use === to check for Matches. ie., identical (===), ;
		if (array[i] == value) {
			return i;
		}
	}
	return ctr;
};

function wc()
{
	if(window.console)
	{
		for(var i = 0; i < arguments.length; i++)
		{
			window.console.log(arguments[i]);
		}
	}
}
