function collectData() {
  var data = {};
  data['name'] = $('#login').val();
  data['passwd'] = $('#pass1').val();
  data['email'] = $('#email').val();
  data['verify'] = $('#verify').val();
  data['verifyId'] = $('#verifyId').val();
  data['default_city'] = $('#default_city').val();
  data['first_name'] = $('#first_name').val();
  data['last_name'] = $('#last_name').val();
  
  return data;
}

function doRegister() {
  var form = $('#SignUpForm');
  
  if ( form.jVal() ) {
    // no error, we can submit this request to server
  	jQuery(document).trigger('loading.facebox');
    var data = collectData();
    $.ajax({
      type: "POST",
      url: "/user/do",
      cache: false,
      dataType: "json",
      data: data,
      success: function(data, status) {
        if ( data["success"] ) {
           window.location = "/my/edit";
        } else {
          $("#"+data["field"]).parent().jValShowWarn(data["msg"]);
        }
      },
      error: function() {
        alert("Failed to connect server");
      }
    });
  }
}

function checkName() {
  var nameField = $('#login');
  if ( nameField.parent().jVal() ) {
    // the name is valid by local check, so server side check.
    var name = nameField.val();
    $.ajax({
      type: "POST",
      url: "/user/check",
      cache: false,
      dataType: "json",
      data: {name: name},
      success: function(data, status) {
        if ( data["success"] ) {
          nameField.parent().jValShowOK('Login name is available.');
        } else {
          nameField.parent().jValShowWarn('Login name is not available.');
        }
      },
      error: function() {
        alert("Failed to connect server");
      }
    });
  }
}

function checkEmail(){
  var nameField = $('#email');
  if ( nameField.parent().jVal() ) {
    // the name is valid by local check, so server side check.
    var name = nameField.val();
    $.ajax({
      type: "Get",
      url: "/user/checkemail",
      cache: false,
      dataType: "json",
      data: {email: name},
      success: function(data, status) {
        if ( data["success"] ) {
          nameField.parent().jValShowOK('email is available.');
        } else {
          nameField.parent().jValShowWarn('email is not available.');
        }
      },
      error: function() {
        alert("Failed to connect server");
      }
    });
  }
}

function refresh(){
	
	var link = $('#refresh').attr('href');
	$.ajax({
	   type: "GET",
	   url: "/user/refresh", 
	   cache: false,
	   dataType: "json", 
	   success: function(data){
	   	  $('#captcha').html(data['image']);
	   	  $('#verifyId').attr('value', data['id']);
	    },
	   error: function() {
        alert("Failed to connect server");
      }
	   }
	);
}
