$.fn.keywait = function(callback,options) {
    options = $.extend({
        rate:  300
    }, options || {});
    var timeout    = null;
    var input=this
    function call(){
        if( $(input).val() != "" ){
            input.callback();
        }
        clearTimeout(timeout);
    }
    this.callback=callback;
    $(this).keyup(function(){
        if(timeout != null){clearTimeout(timeout);}
        timeout = setTimeout(call,options.rate);
    });
}        
htmlReady(function(){
    //$("#login_username").focus();
    
    $("#reg_password").keywait(function(){
        if( $(this).val().length >= 6 ){
             $("#password_entry").addClass("status_ok");
            $("#reg_password_status").html("OK");
        }else{
             $("#password_entry").removeClass("status_ok");
            $("#reg_password_status").html("6 char or longer");
        }
    });
    $("#reg_password2").keywait(function(){
        var pass2 = $(this).val();
        if( pass2.length > 0 && pass2 == $("#reg_password").val() ){
             $("#password2_entry").addClass("status_ok");
            $("#reg_password2_status").html("OK");
        }else{
             $("#password2_entry").removeClass("status_ok");
            $("#reg_password2_status").html("Must match password");
        }
    });
    $("#reg_zip").keywait(function(){
        var zip = $(this).val();
        if( zip.length > 1 ){
             $("#zipcode_entry").addClass("status_ok");
            $("#reg_zip_status").html("OK");
        }else{
             $("#zipcode_entry").removeClass("status_ok");
            $("#reg_zip_status").html("Invalid postalcode");
        }
    });
    
    $("#reg_username").keywait(function() { 
        $.get("/login/check_username/"+$("#reg_username").val()+"/", function(data) {
            if(data=="OK"){
                 $("#username_entry").addClass("status_ok");
            }else{
                 $("#username_entry").removeClass("status_ok");
            }
            $("#reg_username_status").html(data);
        })
    });
    $("#reg_email").keywait(function() {
        $.get("/login/check_email/"+$("#reg_email").val()+"/", function(data) {
            if(data.substr(0,2)=="OK"){
                 $("#email_entry").addClass("status_ok");
            }else{
                 $("#email_entry").removeClass("status_ok");
            }
            $("#reg_email_status").html(data);
        })
    });
    
    $("#reg_birth").change(function() {
        $("#birthyear_entry").addClass("status_ok");
        $("#birthyear_entry .reg_status").html('OK');
    });
    $("#reg_gender").change(function() {
        $("#gender_entry").addClass("status_ok");
        $("#gender_entry .reg_status").html('OK');
    });
});
