$(function() {
	// Showing the login form
	$('a.login').click(function() {					// When the login link is pressed at the top of the page
	  var a = $(this);
	  $.get(a.attr('href'),function(resp){
		var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
		$('body').append(dialog);
		dialog.find(':submit').hide();
		dialog.dialog({
		  title: a.attr('title') ? a.attr('title') : 'Input Form',
		  modal: true,
		  buttons: {
			  'Login': function() {sendFormDetails($(this).find('form')); $(this).dialog('close');},
			  'Cancel': function() {$(this).dialog('close');}
		  },
		  close: function() {$(this).remove();},
		  width: '330px', 
		  show: 'fade', 
		  resizable: false, 
		  draggable: false
		});
	  }, 'html');
	  return false;
	});
	
	function checkLength(o,n,min,max)
	{
		if ( o.val().length > max || o.val().length < min )
		{
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			return false;
		}
		else
		{
			return true;
		}

	}
	
	function checkSimilar(one,two)
	{
		if ( one.val() == two.val() )
		{
			return true;
		}
		else
		{
			two.addClass('ui-state-error');
			updateTips("The passwords do not match.");
			return false;
		}

	}
	
	function updateTips(t)
	{
		$(".validateTips").text(t).addClass('ui-state-highlight');
		setTimeout(function() {
			tips.removeClass('ui-state-highlight', 1500);
		}, 500);
	}


	// Showing the change password form
	$('#passBtn').click(function() {					// When the login link is pressed at the top of the page
		$("<div></div>").load("user/pass.php").dialog({
			title: 'Change password',
			modal: true,
			buttons: {
				'Set': function() {
					var bValid = true;
					$("#pass1, #pass2").removeClass('ui-state-error');
					
					bValid = bValid && checkLength($("#pass1"),"password",3,32);
					bValid = bValid && checkSimilar($("#pass1"),$("#pass2"));					
					
					if (bValid) {
						sendFormDetails("#passChangeForm");
						$(this).dialog('close');
					}
				},
				'Cancel': function() {$(this).dialog('close');}
			},
			close: function() {$(this).remove();},
			width: '330px', 
			show: 'fade', 
		  });
	});
	
	function sendFormDetails(form)
	{
		form = $(form);
		$.ajax({
		  url: form.attr('action'),
		  data: form.serialize(),
		  type: (form.attr('method')),
		  dataType: 'html', 
		  success: 	function(data) {
						  $('<div>'+data+'</div>').dialog({
							  title: form.attr('title'),
							  modal: true,
							  resizable: false,
							  buttons: {
								  'Close': function() {window.location.reload(); $(this).dialog('close');},
							  }
						});
					  }
		});
		return false;
	}
});