// functions for handling AJAX for login
// Assuming the messages are defined
//
var g_info_timer = null;
var g_n_info_timer_tick = 60; // refresh page every 60 calls
function update_server_info(response) {
  // response should have the property 'time', which is server time
  // response may also have property 'points', which is the user's bid points
  if(typeof(response.time)!='undefined') {$('#cur_time').html(response.time);}
  if(typeof(response.points)!='undefined') {$('#logged_in_user_bids').html(response.points);}
}
function refresh_server_info() {
  // get the server time and bid points of user
  if(g_n_info_timer_tick-- <= 0) {location.reload();}
  $.ajax({
    url: 'info.php' ,
    dataType: "json" ,
    success: update_server_info
  });
  if(g_info_timer) {clearTimeout(g_info_timer);}
  g_info_timer = setTimeout('refresh_server_info()',60000); // 1 minute
}
//
function login_handler(id) {
  // returns a login_handler for the login box (with id appended)
  return function(event) {
    event.preventDefault();
    var user_id = $('#tbUserID'+id).val();
    var user_pw = $('#tbPassword'+id).val();
    // some sanity checking
    if(user_id.length <= 0) {
      $('#login_box_msg'+id).html(g_login_msgs['enter_user_id']);
      return false;
    }
    if(user_pw.length <= 0) {
      $('#login_box_msg'+id).html(g_login_msgs['enter_password']);
      return false;
    }
    //
    $.ajax({
	    type: 'POST', 
	    url: 'login.php',
            data: {userId:user_id, password:user_pw},
	    dataType: 'text',
	    timeout: 5000,
	    success: function(msg) {
	    if(msg == 'OK') {
		refresh_server_info();
		$('#logout_box_msg'+id).html('');
		$('#login_box'+id).hide(0);
		$('#gainbid_login_overlay').hide(0);
		// the following two refers to the boxes on the sidebar
		$('#logout_box_msg').html('');
		$('#login_box').hide(0);
		$('#logged_in_user_id').html(user_id);
		$('#logged_in_box').show(0);
	    } else {
		$('#login_box_msg'+id).html(g_login_msgs['login_failed']);
	    }
	    },
	    error: function() {$('#login_box_msg'+id).html(g_login_msgs['login_failed']);}
	});
    return false;
  }
}
function set_login_handler() {
  // setup the handler for login
  var sidebar_login_handler = login_handler('');
  $('#login_button').click(sidebar_login_handler);
  $('#login_form').submit(sidebar_login_handler);
  // the logout button
  $('#logout_button').click(function(event) {
	  event.preventDefault();
	  $.ajax({
	    type: 'POST',
	    url: 'logout.php',
	    dataType: 'text',
            timeout: 5000,
	    success: function(msg) {
		if(msg == 'OK') {
		    location.replace('auctions.php');
		} else {
		    $('#logout_box_msg').html(g_login_msgs['logout_failed']);
		}
              },
            error: function() {$('#logout_box_msg').html(g_login_msgs['logout_failed']);}
	    });
	  return false;
      });
}

// the ready handler
$(function() {
	set_login_handler();
	refresh_server_info();
    });

