$(function() {
	
	var name = $("#name"),
		phone = $("#phone"),
		text = $("#text"),
		allFields = $([]).add(name).add(phone).add(text),
		tips = $("#validateTips");

	function updateTips(t) {
		tips.text(t).effect("highlight",{},1500);
	}

	function checkLength(o,n,min,max) {

		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Længden af " + n + " skal være mellem "+min+" og "+max+" karaktere.");
			return false;
		} else {
			return true;
		}

	}

	function checkRegexp(o,regexp,n) {

		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}

	}
	
	$("#dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 500,
		width: 400,
		modal: true,
		buttons: {
			'Bestil opkald': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				bValid = bValid && checkLength(name,"name",3,16);
				
				bValid = bValid && checkLength(phone,"phone",8,8);
				bValid = bValid && checkRegexp(phone,/^([0-9])+$/i,"Telefon nummeret må kun indeholde 0-9.");
				
				bValid = bValid && checkLength(text,"text",3,450)
				if (bValid) {
					
						document.myform.submit();
					$(this).dialog('close');
					
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		}
	});
	
	
	
	$('#create-user').click(function() {
		$('#dialog').dialog('open');
	})
	.hover(
		function(){ 
			//$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			//$(this).removeClass("ui-state-hover"); 
		}
	).mousedown(function(){
		//$(this).addClass("ui-state-active"); 
	})
	.mouseup(function(){
			//$(this).removeClass("ui-state-active");
	});

});


