$(document).ready(function(){
	//Add target to external links (XHTML-valid)
	$('a.externe-link').attr('target', '_blank');

	//Hovers on breadcrumbs
	$('ul#breadcrumbs a').hover(
		function() { targetli = $(this).parent().prev(); $('a', targetli).addClass('next-hover');},
		function() { targetli = $(this).parent().prev(); $('a', targetli).removeClass('next-hover');}
	);

	//Fancybox links
	$('a.fancy').fancybox({
		'speedIn'		: 300,
		'speedOut'		: 100,
		'titleShow'		: false,
		'overlayOpacity': '0.7',
		'overlayColor'	: '#000',
		'enableKeyboardNavigation': false
	});
	
		//Fancybox links
	$('a.fancytube').fancybox({
		'speedIn'		: 300,
		'speedOut'		: 100,
		'titleShow'		: false,
		'overlayOpacity': '0.7',
		'overlayColor'	: '#000',
		'type'			:	'swf',
		'enableKeyboardNavigation': false
	});

	//Fancybox for image albums in content
	$('ul.albumSlider a.fancy').fancybox({
		'titleShow'		: false,
		'titlePosition'	: 'over',
		'overlayOpacity': '0.7',
		'overlayColor'	: '#000',
		'padding'		: 1
	});

	$('a.close-fancy').live('click',function(){$.fancybox.close();return false;});
	$.datepicker.setDefaults($.datepicker.regional['nl']);
	$('#id_birthday').datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: 'yy-mm-dd',
			monthNamesShort: ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'],
			dayNamesMin: ['Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za', 'Zo'],
			showAnim: 'fadeIn'
		});


	//Sliding menu-options
	$('ul#options li.slide').hover(
		function(){
			$('.opened').stop();
			$('.opened a').stop();
			$(this).removeClass('opened');
			$('ul#options li.opened').each(function(){$(this).animate({width: 20}, 250);});
			$(this).animate({width: 146}, 300);
			$('a', this).animate({width: 80}, 300);
		}, function(){
			$(this).addClass('opened');
			$('.opened').stop();
			$('.opened a').stop();
			$('a', this).animate({width: 0}, 250);
			$(this).animate({width: 62}, 300);
		}
	);

	//Reset opptions
	$('li#options-slider').bind('mouseleave', function(){
		$('.slide').stop();
		$('.slide a').stop();
		$('li.slide a ', this).animate({width: 0}, 250);
		$('li.slide', this).animate({width: 62}, 300);
	});

	//Footer addresses fixed height
	setLocationHeight($('dl#vestigingen'));

	//Click slide locations
	$('dl#vestigingen dt a').click(function(){
		if (!$(this).parent().next('dd').hasClass('opened')) {
				$('dl#vestigingen dd.opened').slideUp(200);
				$('dl#vestigingen dd.opened').removeClass('opened');
				$(this).parent().next('dd').slideDown(200);
				$(this).parent().next('dd').addClass('opened');
			}
			return false;
		}
	);

	//Print
	$('ul#options a.print').click(function(){window.print();return false;});

	//Bookmark
	$('ul#options a.bookmark').click(function(){
		var url = location.href;
		var title = $('title').html();
		if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
			window.external.AddFavorite(url,title);
		} else if (navigator.appName == "Netscape") {
			window.sidebar.addPanel(title,url,"");
		} else { alert("Druk op CTRL+D (Netscape) of CTRL+T (Opera) om op te slaan als favoriet");}
		return false;
	});
	
	//Tell a friend
	$('a.loadtellafriend').live('click', function(){
		$('input#id_link').val(location.href);
		var errors = '';
		if (!isValidEmail($('input#id_friendmail').val())) {
			errors += 'Het e-mailadres van de ontvanger lijkt niet correct te zijn.\n';
		} if (!isValidEmail($('input#id_sendermail').val())) {
			errors += 'Uw e-mailadres lijkt niet correct te zijn.\n';
		} if ($('input#id_sendername').val().trim().length < 2) {
			errors += 'Uw naam is niet ingevuld.\n';
		} if ($('input#id_friendname').val().trim().length < 2) {
			errors += 'De naam van de ontvanger is niet ingevuld.\n';
		} 
		if (errors.length > 1) {
			alert('De e-mail werd niet verzonden, het volgende is fout gegaan:\n\n' + errors);
			return false;
		}
		$.post('/ajax/tellafriend/', $("form#tellafriend").serialize(), function(data){
			$('div.mailexample').html(data);
		});
		$('input#sendmail').val('true');
		
		slideStep($('#stepslider'));
		
		return false;
	});
	$('input#sendtellafriend').live('click', function(){
		$('input#id_link').val(location.href);
		$.post('/ajax/tellafriend/', $("form#tellafriend").serialize(), function(data){
			$('#fancybox-inner').html(data);
		});
		$.fancybox.resize();
		return false;
	});
	
	//Form steps
	$('div.step a.nextstep').live('click', function(){slideStep($('#stepslider'));});
	
	//Remove default form values
	$('input.clickable,textarea.clickable').live('click focusin focusout', function(event) {
		if (event.type == 'click') {
			if ($(this).attr('title')) { //Clicked before
				if ($(this).val() == '') { //Value empty
					$(this).val($(this).attr('title'));
				} else if ($(this).val() == $(this).attr('title')) {
					$(this).val('');
				}
			} else { //First click
				$(this).attr('title', $(this).val());
				$(this).val('');
			}
		} else { //Blur
			if ($(this).val() == '') {
				$(this).val($(this).attr('title'));
			}
		}
	});
	
	//Send form using AJAX
	$('form.ajaxform input:submit').live('click', function(){
		var targetForm = $(this).parents('form:first');
		$.post($(targetForm).attr('action'), $(targetForm).serialize(), function(data){
			$(targetForm).html(data);
		});
		return false;
	});
	
	//Slide through image albums
	$('ul.albumSlider').cycle({fx:'fade',speed:'1500',timeout:'6000'});
	
	$('a.toggle-userpanel').live('click', function(){$('div#userpanel').slideToggle();return false;});
	
	//Registration form
	$('input#reg_username').live('focusout', function() {
		$('div#reg_username_msg').load('/ajax/checkUsernamePresent/' + escape($(this).val()) + '/');
	});
	$('#ac_password').live('keypress', function() {
		var target = $('#ac_pass span');
		var strength = passStrength($(this).val());
		if (strength > 2) { $(target).attr('class', 'exists'); $(target).html('Kan sterker'); }
		if (strength > 50) { $(target).attr('class', 'avi'); $(target).html('Sterk'); }
		if (strength < 3) { $(target).attr('class', 'init'); $(target).html('Kies een wachtwoord'); }
	});
	
	//If class innerclick on field, find first a in there and move there on click
	$('.innerclick').live('click mouseover mouseout', function(event){
		if (event.type == 'click'){location.href = $('a:last', this).attr('href');}
		else if(event.type == 'mouseover' && ! $(this).parent().hasClass('block')){$(this).addClass('hover');}
		else{$(this).removeClass('hover');}
	});
	
	$('table.sortable').tablesorter();

	$('a.toggleDisplayButton').toggle(
		function(){ $('.toggleDisplay').show(); return false; }, 
		function(){ $('.toggleDisplay').hide(); return false; }
	);
	
	$('a.skipfocus').live('focus',function(){$('.fetchfocus:first').focus();});
	
	//Search redirect
	$('.zoekformulier input:submit').live('click', function(){
		var targetForm = $(this).parents('form:first');
		var term = escape($('.zoekterm', targetForm).val().replace(/[^\w ]/g, ''));
		location.href = '/search/' + term + '/?utm_q=' + term;
		return false;
	});

	/* File manager
	 -------------------------------------------------------- */
	$('form.control #page_id').val($('input#cms-page-id').val());
	$('ul.rootnode li.folder span').live('click', function() {
		
		// Open / close tree
		var target = $('ul.files:first', $(this).parent());
		if ($(target).hasClass('opened')) {
			$(target).slideUp('fast');
			$(target).removeClass('opened');
		} else {
			$(target).slideDown('fast');
			$(target).addClass('opened');
		}
		
		// Select
		$('select#id_folder').val(
			$(this).attr('title')
		);
		
		return false;
	});
	$('#fancybox-inner ul.rootnode li.file a').live('click', function() {
		$('#id_link').val('/media/share/closed' + $(this).attr('title'));
		$('#id_link').addClass('active');
		$('#id_link').select();
		return false;
	});
	$('#open-file-upload').live('click', function() {
		$('form.control div.hidden:visible').slideUp('fast');
		$('#file_upload').slideDown();
		$('#form_action').val('upload');
		return false;
	});
	$('#open-create-dir').live('click', function() {
		$('form.control div.hidden:visible').slideUp('fast');
		$('#create-dir').slideDown();
		$('#form_action').val('createdir');
		return false;
	});
	$('#open-remove-dir').live('click', function() {
		$('form.control div.hidden:visible').slideUp('fast');
		$('#remove-dir').slideDown();
		$('#form_action').val('removedir');
		return false;
	});
	$('#open-ftp').live('click', function() {
		var target = $('table.ftpinfo');
		if ($(target).hasClass('opened')) {
			$(target).slideUp();
			$(target).removeClass('opened');
		} else {
			$(target).slideDown();
			$(target).addClass('opened');
		}
		return false;
	});
	$('form.control input.submit').live('click', function() {
		$.post('/admin/filemanager/' + pageId + '/', $("form.control").serialize(), function(data){
			$('#fancybox-inner').html(data);
		});
		return false;
	});
	
	$('div#ajax_preloader').ajaxStart(function(){$(this).slideDown('fast');});
	$('div#ajax_preloader').ajaxStop(function(){$(this).slideUp('fast');});
	
	$('.toggleVisibleArea').live('click',function(){
		$('.invisibleArea').each(function(){
			if($(this).hasClass('opened')){$(this).removeClass('opened');$(this).slideUp();
			}else{$(this).addClass('opened');$(this).slideDown();}
		});
	});
	
	setTiny();
});

function setLocationHeight(target){
	initHeight = $(target).height() - $('dd:first',target).height();
	largestDd = $('dd:first',target).height();
	$('dd', target).each(function(){
		if($(this).height() > largestDd ){
			largestDd = $(this).height();
		}
	});
	$(target).css('height', (initHeight + largestDd + 20));
}

function passStrength(password) {
	var points = password.length + 1;
	if (password.match(/[A-Z]/g)) points *= 2;
	if (password.match(/[a-z]/g)) points *= 2;
	if (password.match(/[0-9]/g)) points *= 2;
	return (points > 100) ? 100 : points;
}

function isValidEmail(str){return(str.indexOf(".")>1)&&(str.indexOf("@")>1);}

function setTiny() {
	$('textarea.tiny').tinymce({
		script_url : '/media/scripts/tiny_mce/tiny_mce.js',
		content_css : '/media/css/site.css',
		theme : "advanced",
		plugins : "style,table,advlink,media,paste,xhtmlxtras",
		theme_advanced_buttons1 : "bold,italic,|,charmap,|,cut,copy,paste,pasteword,|,bullist,numlist,|,undo,redo,|,link,unlink,|,tablecontrols,|,removeformat,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		language : "nl",
		paste_auto_cleanup_on_paste : true,
        paste_preprocess : function(pl, o) {
            // Content string containing the HTML from the clipboard
        },
        paste_postprocess : function(pl, o) {
            // Content DOM node containing the DOM structure of the clipboard
			var ed = pl.editor, dom = ed.dom;
            
            // Remove all tags which are not <p> or <br>
            tinymce.each(dom.select('*', o.node), function(el) 
            {   
				if (el.tagName.toLowerCase() != "p" && el.tagName.toLowerCase() != "a") 
                {
					dom.remove(el, 1); // 1 = KeepChildren
                }
                dom.setAttrib(el, 'style', '');
            });

        }
		

	});
}

function slideStep(targetWrapper) {
	var oldMargin = parseInt($(targetWrapper).css('margin-left'));
	var stepWidth = parseInt($('div.step').width());
	$(targetWrapper).animate({'margin-left':(oldMargin - stepWidth)});
	return false;
}
