﻿// jQuery validation functions for the registration screen.
// Requires jQuery :)

var checkErrorIntervalId;

$(function(){    
    
    $("input").blur(function(){
        checkErrorIntervalId = setTimeout(checkInputError,10);
        return true;
    });   
    $("#tr-username input").blur(checkUserName);
    $(".password").pstrength();
    //$("input.text").get(0).focus();
    $("form").submit(function(){        
        checkErrorIntervalId = setTimeout(checkInputError,10);
        return true;
    });
    checkErrorIntervalId = setTimeout(checkInputError,10);
});

function checkInputError(){
    var errorClass = "input-error";
    $("td:has(.error:hidden) span.input-error").removeClass(errorClass);
    $("fieldset:has(.error:visible)").addClass(errorClass).find("td:has(.error:visible) span.input").addClass(errorClass);    
    $("fieldset:has(.error:hidden)").not(":has(.error:visible)").removeClass(errorClass);
    clearTimeout(checkErrorIntervalId);
}

// Checks to see if the username is available
function checkUserName(){
    //var btnHtml = btn.innerHTML;
    var userVal = $.trim($("#tr-username .text").val());    
    var $msg = $("#user-avail-msg");
    
    if (userVal.length<4){        
        //$msg.html("Sorry, your username must be more than 3 characters&nbsp;long.").show().get(0).className="invalid";        
        return false;
    }
    
    //btn.disabled = true;
    //btn.innerHTML = "checking..";
    
    $.getJSON(window.location.pathname + "?username=" + userVal, function(json){        
        //btn.disabled = false;
        //btn.innerHTML = btnHtml;
        
        if (json.isAvailable){
            if ($msg.html()!=""){ // Only show success if an error has happened
                $msg.html("<strong>" + userVal + "</strong> is available!").get(0).className = "valid";
                $msg.get(0).style.display = 'block';
                checkErrorIntervalId = setTimeout(checkInputError,10);
            }                        
        } else {
            $msg.html("Sorry, <strong>" + userVal + "</strong> is not available.<em>Please try a different username.</em>").get(0).className = "error";            
            $msg.get(0).style.display = 'block';
            checkErrorIntervalId = setTimeout(checkInputError,10);
        }
        
        
    });
}
