jQuery.fn.extend(
{
	accordion: function()
	{
		var $accordion = $(this);
		$accordion.children('ul').hide();
		$accordion.children('h3').click(function(e)
		{
			var $menu = $(this).next();
			
			if($menu.is('ul'))
			{
				if($menu.is(':visible'))
				{
					return false;
				}
				
				$accordion.children('h3').removeClass('active');
				$accordion.children('ul:visible').slideUp(150);
				$menu.slideDown(150);
				$(this).addClass('active');
			}
		});
		
		$accordion.children('h3:first').addClass('active');
		$accordion.children('ul:first').show();
	},

	getID: function()
	{
		return /\d+$/.exec($(this).attr('id'))[0];
	},

	scrollTo: function(speed, easing)
	{
		return this.each(function()
		{
			var targetOffset = $(this).offset().top;
			$('html, body').animate({scrollTop: targetOffset}, speed, easing);
		});
	}
});

var forumsPulldown =
{
	animating: false,
	mouseOver: false,
	open: false,
	
	clearTimeout: function()
	{
		clearTimeout(forumsPulldown.timeout);
	},

	hide: function()
	{
		if(!this.animating && this.open)
		{
			forumsPulldown.animating = true;
			
			$('#forumsPulldown').slideUp(100, function() {
				forumsPulldown.animating = false;
				forumsPulldown.open = false;
			});
		}
	},
	
	init: function()
	{
		$('#forumsPulldownTab').mouseover(forumsPulldown.show);
		$('#forumsPulldownTab').mouseout(forumsPulldown.setTimeout);
		$('#forumsPulldownWrapper a').mouseover(forumsPulldown.clearTimeout);
		$('#forumsPulldownWrapper a').mouseout(forumsPulldown.setTimeout);
	},
	
	setTimeout: function()
	{
		forumsPulldown.mouseOver = false;
		forumsPulldown.timeout = setTimeout('forumsPulldown.hide();', 10);
	},
	
	show: function()
	{
		if(!this.animating && !this.open)
		{
			forumsPulldown.animating = true;
			forumsPulldown.mouseOver = true;
			
			$('#forumsPulldown').slideDown(300, function() {
				forumsPulldown.animating = false;
				forumsPulldown.open = true;
				
				if(!forumsPulldown.mouseOver)
				{
					forumsPulldown.hide();
				}
			});
		}
		else
		{
			clearTimeout(this.timeout);
		}
	}
};

var murov =
{
	account:
	{
		cropper:
		{
			setCoords: function(x, y)
			{
				$('#offsetX').val(x);
				$('#offsetY').val(y);
			},
					
			setScale: function(scale)
			{
				$('#scale').val(scale);
			}
		},
		
		forgotPassword:
		{
			submit: function()
			{
				if(!murov.utils.checkEmpty('email', 'Nog even je e-mailadres invullen.')) return false;
				return true;
			}
		},
		
		profile:
		{
			init: function()
			{
				$('select[name^=dob]').change(function()
				{
					$('#dobEdit').val(1);
				})
			}
		},
		
		register:
		{
			checkUsername: function(element)
			{
				if($('#userUsername').val())
				{
					$('#usernameLoader').show();
					$("#usernameCheck").load('/account/check-username/', {username: $('#userUsername').val()}, function()
					{
						$('#usernameLoader').hide();	
					});
				}
			},
			
			init: function()
			{
				$('#usernameLoader').hide();
				$('#userUsername').keyup(murov.account.register.checkUsername);
				$('#registration').submit(murov.account.register.submit);
			},
			
			submit: function()
			{
				if(!murov.utils.checkEmpty('userUsername', 'Nog even een gebruikersnaam invullen.')) return false;
				if(!murov.utils.checkEmpty('userPassword', 'Nog even een wachtwoord invullen.')) return false;
				if(!murov.utils.checkEmpty('userEmail', 'Nog even je e-mailadres invullen.')) return false;
				
				if($('#userPassword').val().length < 6)
				{
					alert('Je wachtwoord moet minstens 6 tekens lang zijn.');
					$('#userPassword').focus();
					return false;
				}
				
				if($('#userPassword').val() != $('#passwordConfirm').val())
				{
					alert('Wachtwoorden komen niet overeen.');
					$('passwordConfirm').focus();
					return false;
				}
				
				if(!$('#terms').is(':checked'))
				{
					alert('Nog even de regels accepteren.');
					return false;
				}				
				
				return true;
			}
		},
		
		settings:
		{
			init: function()
			{
				$('#settings').submit(murov.account.settings.submit);
			},
		
			submit: function() {
				if(!murov.utils.checkEmpty('userEmailNew', 'Nog even je e-mailadres invullen.')) return false;

				if($('#userPassword').val().length && $('#userPassword').val().length < 6)
				{
					alert('Je wachtwoord moet minstens 6 tekens lang zijn.');
					$('#userPassword').focus();
					return false;
				}
				
				if($('#userPassword').val() != $('#passwordConfirm').val())
				{
					alert('Wachtwoorden komen niet overeen.');
					$('passwordConfirm').focus();
					return false;
				}
				
				return true;
			}
		},
		
		subscriptions:
		{
			init: function()
			{
				$(':checkbox.toggle').click(murov.utils.toggleCheckboxes);
				$('#subscriptions').submit(murov.account.subscriptions.submit);
			},
			
			submit: function()
			{
				return confirm('Weet je zeker dat je de geselecteerde abonnementen wilt verwijderen?');
			}
		},
		
		sign_in:
		{
			init: function()
			{
				$("#signInBox").fadeOut(500).fadeIn(500);
			},
		
			submit: function()
			{
				if(!murov.utils.checkEmpty('signInUsername', 'Nog even je gebruikersnaam invullen.')) return false;
				if(!murov.utils.checkEmpty('signInPassword', 'Nog even je wachtwoord invullen.')) return false;
				return true;
			}
		}
	},
	
	main:
	{
		newsletterSubscribe: function(e)
		{
			e.preventDefault();
			if(!murov.utils.checkEmpty('subscriberEmail', 'Nog even je e-mailadres invullen.')) return false;
			
			$.post('/main/newsletter-subscribe/', $(this).serialize(), function(data)
			{
				$('#newsletter').html(data).fadeIn();
				$('#errorsWrapper').slideDown();
				murov.utils.initSampleInput();
			});
		}
	},
	
	message:
	{
		create:
		{
			addSuggestItem: function(e)
			{
				e.preventDefault();
				
				if(e.which == 13 && $('#suggest option:selected').length)
				{
					var username = $('#suggest option:selected').text();
					var recipients = $('#recipients').val().split(',');
					recipients.pop();
					recipients.push(username);
					
					for(var i = 0, len = recipients.length; i < len; ++i)
					{
						recipients[i] = $.trim(recipients[i]);
					}
					
					$('#recipients').val(recipients.join(', ')).focus();
					$('#suggest').hide();
				}
			},
		
			init: function()
			{
				$('#recipients').keyup(murov.message.create.suggest);
			},
			
			suggest: function(e)
			{
				if(e.which == 40)
				{
					$('#suggest select').focus().children(':first').attr('selected', 'selected');
				}
				else
				{
					var $select = $('<select></select>');
					$select.keypress(murov.message.create.addSuggestItem);
					$select.attr('multiple', 'multiple');
					$select.attr('size', 8);
					var recipients = $(this).val().split(',');
				
					for(var i = 0, len = recipients.length; i < len; ++i)
					{
						recipients[i] = $.trim(recipients[i]).toLowerCase();
					}
					
					var last = recipients[recipients.length - 1];
					var regExp = new RegExp('^' + last + '.+', 'i');
					
					if(last.length)
					{
						var $option;
						var count = 0;
					
						$.each(usernames, function()
						{
							if(this.match(regExp) && $.inArray(this.toString().toLowerCase(), recipients) == -1)
							{
								count++;
								$option = $('<option></option>');
								$option.text(this.toString());
								$option.attr('value', this.toString());
								$select.append($option);
							}
						});
						
						if(count)
						{
							if(count < 8)
							{
								$select.attr('size', count);
							}
						
							$('#suggest').html($select).show();
						}
					}
					else
					{
						$('#suggest').html($select).hide();
					}
				}
			}
		},
	
		inbox:
		{
			init: function()
			{
				$(':checkbox.toggle').click(murov.utils.toggleCheckboxes);
				$('#inbox').submit(murov.message.inbox.submit);
			},
		
			submit: function()
			{
				return confirm('Weet je zeker dat je de geselecteerde berichten wilt verwijderen?');
			}
		},
		
		view:
		{
			edit: function(e)
			{
				e.preventDefault();		
				var id = $(this).getID();
				$('#viewMessage' + id).hide();
				$('#editMessage' + id).show();
				$.get('/message/edit/' + id + '/', {}, function(data)
				{
					$('#editMessage' + id).html(data);
					$('#editForm' + id).submit(murov.message.view.editSave);
					$('.editMessageCancel').click(murov.message.view.editCancel);
				});
			},
		
			editCancel: function(e)
			{
				e.preventDefault();		
				var id = $(this).getID();
				$('#editMessage' + id).hide();
				$('#viewMessage' + id).show();
			},
		
			editSave: function(e)
			{
				e.preventDefault();
				var id = $(this).getID();
				if(!murov.utils.checkEmpty('messageBodyTextarea' + id, 'Nog even een bericht invullen.')) return false;
			
				$('#editMessage' + id).html('<img alt="" src="/img/loader.gif" />');
				$.post('/message/edit/' + id + '/', $(this).serialize(), function(data)
				{
					$('#messageBody' + id).html(data);
					$('#editMessage' + id).hide();
					$('#viewMessage' + id).show();
				});
			},
		
			init: function()
			{
				$('#replyForm').submit(murov.message.view.submit);
				$('a.editMessageLink').click(murov.message.view.edit);
			},
			
			submit: function()
			{
				if(!murov.utils.checkEmpty('messageBody', 'Nog even een bericht invullen.')) return false;
				return true;
			}
		}
	},
	
	shop:
	{
		init: function()
		{
			$('dd a[id^=show]').click(function(e)
			{
				e.preventDefault();
				var initial = $(this).attr('id').substr(-1);
				$('#brands' + initial).show();
				$('#show' + initial).hide();
			});
			
			$('dd a[id^=hide]').click(function(e)
			{
				e.preventDefault();
				var initial = $(this).attr('id').substr(-1);
				$('#brands' + initial).hide();
				$('#show' + initial).show();
			});			
		},

		view:
		{
			edit: function(e)
			{
				e.preventDefault();		
				var id = $(this).getID();
				$('#viewShopComment' + id).hide();
				$('#editShopComment' + id).show();
				$.get('/shop_comment/edit/' + id + '/', {}, function(data)
				{
					$('#editShopComment' + id).html(data);
					$('#editForm' + id).submit(murov.shop.view.editSave);
					$('.editShopCommentCancel').click(murov.shop.view.editCancel);
				});
			},
			
			editCancel: function(e)
			{
				e.preventDefault();		
				var id = $(this).getID();
				$('#editShopComment' + id).hide();
				$('#viewShopComment' + id).show();
			},
		
			editSave: function(e)
			{
				e.preventDefault();
				var id = $(this).getID();
				if(!murov.utils.checkEmpty('shopCommentBodyTextarea' + id, 'Nog even een bericht invullen.')) return false;
			
				$('#editShopComment' + id).html('<img alt="" src="/img/loader.gif" />');
				$.post('/shop_comment/edit/' + id + '/', $(this).serialize(), function(data)
				{
					$('#shopCommentBody' + id).html(data);
					$('#editShopComment' + id).hide();
					$('#viewShopComment' + id).show();
				});
			},

			init: function()
			{
				$('.editShopCommentLink').click(murov.shop.view.edit);
				$('#previewButton').click(murov.shop.view.preview);
				$('#shopCommentForm').submit(murov.shop.view.submit);
				
				if(shopCommentId = $.query.get('shop_comment_id'))
				{
					$('#shopComment' + shopCommentId).scrollTo(500).fadeOut(500).fadeIn(500);
				}
			},
			
			preview: function(e)
			{
				e.preventDefault();
				$.post('/shop_comment/preview/', $('#shopCommentForm').serialize(), function(data)
				{
					$('#preview').html(data).scrollTo(500).fadeOut(500).fadeIn(500);
				});
			},
			
			submit: function()
			{
				console.log($('#shopCommentBody').val());
				if(!murov.utils.checkEmpty('shopCommentBody', 'Nog even een bericht invullen.')) return false;
				return true;
			}
		}
	},
	
	topic:
	{
		create:
		{
			addAnswer: function(e)
			{
				e.preventDefault();
				var $answer = $('#answerDummy').clone();
				$answer.children('div.left').html(++numAnswers + '.');
				$('#pollAnswers').append($answer);
				$('#answer' + numAnswers + ' input').focus();
				
				if(numAnswers == 10)
				{
					$('#addAnswer').hide();	
					return false;
				}
				
				$('#pollAnswers a').unbind();
				$('#pollAnswers a').bind('click', murov.topic.create.removeAnswer);
				
			},
			
			init: function()
			{
				$('#addAnswer').click(murov.topic.create.addAnswer);
				$('#previewButton').click(murov.topic.create.preview);
				$('#topicForm').submit(murov.topic.create.submit);
			},
			
			preview: function(e)
			{
				e.preventDefault();
				$.post('/topic/preview/', $('#topicForm').serialize(), function(data)
				{
					$('#preview').html(data).scrollTo(500).fadeOut(500).fadeIn(500);
				});
			},
		
			removeAnswer: function(e)
			{
				e.preventDefault();
				$(e.currentTarget).parent().remove();
				var answers = 0;
				
				$('#pollAnswers .field:visible div.left').each(function()
				{
					$(this).html(++answers + '.');
				});			
			},
		
			submit: function()
			{
				if(!murov.utils.checkEmpty('topicSubject', 'Nog even een onderwerp invullen.')) return false;
				if(!murov.utils.checkEmpty('postBody', 'Nog even een bericht invullen.')) return false;
				
				if($('#poll').length)
				{
					if(!murov.utils.checkEmpty('inputAnswer1', 'Vul minstens twee antwoorden in.')) return false;
					if(!murov.utils.checkEmpty('inputAnswer2', 'Vul minstens twee antwoorden in.')) return false;
				}
				
				$('#submit').unbind('click').attr('type', 'button').html('Bezig&hellip;');
				$('#busyMessage').fadeIn();
			},
		},
	
		view:
		{
			edit: function(e)
			{
				e.preventDefault();		
				var id = $(this).getID();
				$('#viewPost' + id).hide();
				$('#editPost' + id).show();
				$.get('/topic/edit/' + id + '/', {}, function(data)
				{
					$('#editPost' + id).html(data);
					$('#editForm' + id).submit(murov.topic.view.editSave);
					$('.editPostCancel').click(murov.topic.view.editCancel);
				});
			},
			
			editCancel: function(e)
			{
				e.preventDefault();		
				var id = $(this).getID();
				$('#editPost' + id).hide();
				$('#viewPost' + id).show();
			},
			
			editSave: function(e)
			{
				e.preventDefault();
				var id = $(this).getID();
				if(!murov.utils.checkEmpty('postBodyTextarea' + id, 'Nog even een bericht invullen.')) return false;
			
				$('#editPost' + id).html('<img alt="" src="/img/loader.gif" />');
				$.post('/topic/edit/' + id + '/', $(this).serialize(), function(data)
				{
					$('#postBody' + id).html(data);
					$('#editPost' + id).hide();
					$('#viewPost' + id).show();
				});
			},
		
			init: function()
			{
				$('.editPostLink').click(murov.topic.view.edit);
				$('.showVotes').click(murov.topic.view.showVotes);
				$('#poll').submit(murov.topic.view.vote);
				$('#previewButton').click(murov.topic.view.preview);
			
				if(postId = $.query.get('post_id'))
				{
					$('#post' + postId).scrollTo(500).fadeOut(500).fadeIn(500);
				}
			
				$('input[id^=subscribe]').click(function(e)
				{
					var id = $(this).getID();
					var subscribe = $(this).is(':checked') ? 1 : 0;
					new $.post('/account/toggle_subscription/' + id, {subscribe: subscribe});				
				});
			},
			
			preview: function(e)
			{
				e.preventDefault();
				$.post('/topic/preview/', $('#replyForm').serialize(), function(data)
				{
					$('#preview').html(data).scrollTo(500).fadeOut(500).fadeIn(500);
				});
			},
			
			showVotes: function(e) {
				e.preventDefault();			
				$('#pollWrapper').load('/topic/vote/' + id + '/');
			},
			
			vote: function(e) {
				e.preventDefault();
				$('#pollWrapper').load($(this).attr('action'), $(this).serialize());
			}
		},
	},
	
	utils:
	{
		checkEmpty: function(id, message)
		{
			var element = $('#' + id);
		
			if(!$.trim(element.val()))
			{
				alert(message);
				element.focus();
				return false;		
			}
			
			return true;
		},
		
		init: function()
		{
			var pathParts = window.location.pathname.split('/');
			var obj = murov;
			
			$.each(pathParts, function()
			{
				part = this.replace('-', '_');
			
				if(typeof(obj[part]) == 'object')
				{
					obj = obj[part];
				}
			});
			
			if(typeof(obj.init) == 'function')
			{
				obj.init();
			}
		},
		
		initExternalLinks: function()
		{
			$('a[href*="://"]').attr('target', '_blank');	
		},
		
		initSampleInput: function()
		{
			$('input.sample').blur(function()
			{
				if($.trim($(this).val()) == '')
				{
					$(this).addClass('sample');
					$(this).val($(this).attr('defaultValue'));
				}
			});
		
			$('input.sample').focus(function()
			{
				if($.trim($(this).val()) == $(this).attr('defaultValue'))
				{
					$(this).removeClass('sample');
					$(this).val('');
				}
			});
		},
		
		resizeImage: function()
		{
			$image = $(this);
			var maxWidth = $image.parent().parent().width();

			if($image.width() > maxWidth)
			{
				$image.height(parseInt($image.height() * (maxWidth / $image.width())));
				$image.width(maxWidth);
			}
			
			return $image;
		},
		
		toggleCheckboxes: function(e)
		{
			var checked = $(this).attr('checked');
			var id = $(this).attr('id');
			
			$(':checkbox[id^=' + id + ']').each(function(i)
			{
				$(this).attr('checked', checked);
			});
		}
	}
};

var textarea =
{
	init: function()
	{
		$('a.insert').unbind('click mousedown mouseup');
		
		$('a.insert').bind('mousedown mouseup', function(e)
		{
			$(this).toggleClass('down');
		});
		
		$('a.insert').click(function(e)
		{
			var action = $(this).attr('id').replace('insert', '').toLowerCase();
			var id = $(this).parents('.textareaWrapper').children('textarea').attr('id');
						
			switch(action)
			{
				case 'bold':
					textarea.insertTag(id, '[b]', '[/b]', 'vet');
					break;

				case 'image':
					textarea.insertTag(id, '[img]', '[/img]', 'http://');
					break;
					
				case 'italic':
					textarea.insertTag(id, '[i]', '[/i]', 'cursief');
					break;

				case 'link':
					textarea.insertTag(id, '[url=http://]', '[/url]', 'gelinkte tekst');
					break;
					
				case 'list':
					textarea.insertTag(id, '[list]\n[*]', '[/*]\n[/list]\n', 'lijst item');
					break;
					
				case 'maillink':
					textarea.insertTag(id, '[mail=abc@xyz.com]', '[/mail]', 'gelinkte tekst');
					break;
					
				case 'numlist':
					textarea.insertTag(id, '[numlist]\n[*]', '[/*]\n[/numlist]\n', 'lijst item');
					break;
					
				case 'soundcloud':
					textarea.insertTag(id, '[soundcloud]', '[/soundcloud]\n', 'SoundCloud URL');
					break;					
					
				case 'video':
					textarea.insertTag(id, '[video]', '[/video]', 'YouTube of Vimeo URL');
					break;				
					
				default:
					break;
			}
			
			e.preventDefault();
		});
	},
	
    insertTag: function(id, openTag, closeTag, defaultText)
    {
        var area = document.getElementById(id);    
        var selection = document.selection;

        if(selection)
        {
            var selectedText = selection.createRange().text || defaultText;
			area.focus();
            
            if(selectedText.charAt(selectedText.length - 1) == ' ')
            {
                selectedText = selectedText.substring(0, selectedText.length - 1);
                selection.createRange().text = openTag + selectedText + closeTag + ' ';
            }
            else
            {
				selection.createRange().text = openTag + selectedText + closeTag;
            }
        }
        else if(typeof(area.selectionStart) == 'number')
        {
            var replaced = false;
            var startPos = area.selectionStart;
            var endPos = area.selectionEnd;
            var scrollTop = area.scrollTop;
            var text = (area.value).substring(startPos, endPos) || defaultText;

            if(endPos - startPos)
            {
				replaced = true;
            }
            
            if(text.charAt(text.length - 1) == ' ')
            {
				replaceWith = openTag + text.substring(0, (text.length - 1)) + closeTag + ' ';
            }
            else
            {
                replaceWith = openTag + text + closeTag;
            }
            
            area.value = area.value.substring(0, startPos) + replaceWith + area.value.substring(endPos, area.value.length);
            area.focus();

            if(replaced)
            {
				var caretPos = startPos + (openTag.length + text.length + closeTag.length);
				area.selectionStart = caretPos;
				area.selectionEnd = caretPos;
            }
            else
            {
                area.selectionStart = startPos + openTag.length;
                area.selectionEnd = startPos + openTag.length + text.length;
            }
            
			area.scrollTop = scrollTop;
        }
        
        if(area.createTextRange)
        {
			area.caretPos = selection.createRange().duplicate();
        }
        
        return false;
    }
};

$(document).ready(function()
{
	forumsPulldown.init();
	murov.utils.init();
	murov.utils.initExternalLinks();
	murov.utils.initSampleInput();
	
	$('.button, button').mousedown(function() { $(this).addClass('active') }).mouseup(function() { $(this).removeClass('active') });
	$('.cancel').click(function(e) { history.back() });
	$('#accordion').accordion();
	$('#subscriberForm').submit(murov.main.newsletterSubscribe);
	$('#signIn').submit(murov.account.sign_in.submit);
	$('#errorsWrapper').slideDown();
	$('#flashWrapper').slideDown();
});

Cufon.replace('h1 a');