﻿
$(function() {
		
		var name = $("#name"),
			password = $("#password"),
			allFields = $([]).add(name).add(password),
			tips = $("#validateTips");

		function updateTips(t) {
			tips.text(t);
		}

		function checkLength(o,n,min,max) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}

		}
		function VerificaUsuario(u,p)
		{
		var usuario= u.val();
		var contra = p.val();
		var return_value= $.ajax({ 
				type: "POST", 
				url: "../Inicio/verificaUsuarioDB.asp",
				data: "login="+encodeURIComponent(usuario)+"&pass="+encodeURIComponent(contra),
				dataType: "html",
				async: false }).responseText;	
		if (return_value == "Verdadero"){
				return true;
			}else{
				updateTips("el Usuario ó la Contraseña no son válidas");
				return false;	
			}
		}
		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: 300,
			modal: true,
			buttons: {
				'Entrar': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(name,"Porfavor ingresa un usuario válido",1,18);
					bValid = bValid && checkLength(password,"Porfavor ingresa una contraseña válida",1,18);
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					bValid = bValid && VerificaUsuario(name,password);

					if (bValid) {
						window.location="../Menu/Index.asp";
						$(this).dialog('close');
					}
				},
				Cancelar: 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");
		});

	});
