$(document).ready(bindEvents);
function bindEvents() {
  $("#signuparea input").bind('change keyup',validate_registration);
  $("#gid").bind('change keyup', validate_house);
  $("#house_submit").bind('click', join_house);
  $("#leave_button").bind('click', leave_house);
$("#group_create input").bind('change keyup', validate_new_house);
}

function validate_registration() {
   var length_of_fname = $("#fname").val().length;
   var length_of_lname = $("#lname").val().length;
   var length_of_uname = $("#new_uname").val().length;
   var length_of_pass = $("#new_pass").val().length;
   var length_of_email = $("#email").val().length;
   if (length_of_fname > 0 &&
   	length_of_lname > 0 &&
   	length_of_uname > 0 &&
   	length_of_pass > 0 &&
   	length_of_email > 0) {
   	$("#register_submit").attr("disabled",false);
   }
}   
function validate_house(event) {
    value = $(event.target).val();
    $("#house_submit").attr("disabled", true);
    $("#password_enter").hide();
    $("#grp_progress").text("Checking for house");
    $.post("groups.php", {'op' : 'groupexists', 'gid': value}, validate_house_callback);
}
function validate_house_callback(data, textStatus) {
    var house_exists = eval(data);
    if (house_exists != false) {
	$("#grp_progress").html("Name: <i>" + data + "</i>");
	$("#password_enter").show('medium');
	$("#house_submit").attr("disabled", false);
    } else {
	$("#grp_progress").text("The house you entered does not exist");
	$("#password_enter").hide();
    }
}
function join_house(event) {
    var group_id = $("#gid").val();
    var password = $("#jgpass").val();
    $.post("group_join.php", {'group_id': group_id, 'password': password}, join_house_callback);
}
function leave_house() {
    $.post("group_join.php", {'group_id': 0}, function() { window.location.reload(true) });
}
function join_house_callback(data, textStatus) {
    var result = eval(data);
    if (result[0] == true) {
	window.location.reload(true);
    } else {
	alert("Could not join house: " + result[1]);
    }
}
function validate_new_house(event) {
var new_house_name_length = $("#gname").val().length;
var new_house_password = $("#gpass").val().length;
var new_house_fee = $("#gfee").val().length;
if (new_house_name_length > 0 & new_house_password > 0 && new_house_fee > 0) {
	$("#create_house_submit").attr("disabled", false);
} else {
$("#create_house_submit").attr("disabled", true);
}
}