$(function() {
	
	var name = $("#name"),
		email = $("#email"),
		password = $("#dpassword"),
		allFields = $([]).add(name).add(email).add(password),
		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("Length of " + n + " must be between "+min+" and "+max+".");
			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: 260,
		modal: true,
		resizable: false,
		position: 'center',
		buttons: {
			'Login': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				bValid = bValid && checkLength(name,"username",5,20);
				bValid = bValid && checkLength(password,"password",5,20);

				bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
				bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
				
				if (bValid) {
					var dataString = 'username=' + name.val() + '&password=' + password.val();
					$.ajax({
				    	type: "POST",
				    	url: "/dealers/login",
				    	data: dataString,
						dataType: "text",
				    	success: function(msg) {
							if (msg == 'success') {
								location.reload();
							}
							if (msg == 'error') {
								var showMsg = 'Login incorrect, please try again.'
								$('html, body').animate({scrollTop:0}, 'slow');
								$('#flash').fadeOut("fast");
								$('#flash').fadeIn("slow").text(showMsg);
							}
							if (msg == 'transition') {
								window.location="/dealers/register";
							}
							if (msg == 'wccshop') {
								window.location="/dealers/change";
							}
				    	}
					});
					
					$(this).dialog('close');
				}
			},
			Cancel: function() {
				$(this).fadeOut("slow").dialog('close');
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		}
	});
	
	$('#create-user').click(function() {
		$('#dialog').fadeIn("slow").dialog('open');
	})

});
