////////////////////////////////////////////////////////////////////////////////////////
// The following are functions for refreshing the page for the auctions
////////////////////////////////////////////////////////////////////////////////////////
// Assumes dialog.js has been loaded, so that we can use our own alert box.
//
function format_auction_time_remain(time_remain) {
  // time_remain is the number of seconds remaining
  // 1 min is 60 sec
  // 1 hr  is 3600 sec
  // 1 day is 86400 sec
  if(time_remain < 0) return '';
  var days = Math.floor(time_remain/86400);
  var hrs = Math.floor((time_remain%86400)/3600);
  var mins = Math.floor((time_remain%3600)/60);
  var secs = time_remain%60;
  var r = (secs < 10 ? '0' : '') + secs;
  r = (mins < 10 ? '0' : '') + mins + ':' + r;
  if(hrs > 0)  r = '' + hrs  + ':' + r;
  if(days > 0) r = '' + days + 'd ' + r;
  return r;
}
function time_remain_class(time_remain) {
  if(time_remain < 0) return 'normal';
  if(time_remain <= 10) return 'tensec';
  if(time_remain <= 30) return 'halfmin';
  if(time_remain <= 60) return 'onemin';
  if(time_remain <= 120) return 'twomin';
  return 'normal';
}
function update_auction(auc,is_top) {
   // auc is an associative array that should include:
   //   id: auction ID
   //   top_bidders: an array of user ID names, in the order of the top bidders
   //   bid_price: current bidding price
   //   time_remain: the number of seconds remaining for the auction, being negative means the auction has ended.
   //   status: the current status of the auction, N for normal, S for suspended, E for ended
   $('#bid_price' + auc.id).html('HKD ' + auc.bid_price);
   $('#top_bidder' + auc.id).html(auc.top_bidder);
   $('#time_remain' + auc.id).html(format_auction_time_remain(auc.time_remain));
   $('#time_remain' + auc.id).attr('class',time_remain_class(auc.time_remain));
   if(auc.time_remain < 0 || auc.status==1) {
     $('#' + auc.id).unbind('click');
     $('#' + auc.id).click(function(event) {event.preventDefault();});
   } else {
     $('#' + auc.id).unbind('click');
     $('#' + auc.id).click(bidlink_handler);
   }
   if(auc.time_remain < 0 && typeof(auc.top_bidder)!='undefined' && auc.top_bidder!=null) {
     $('#bidnav' + auc.id).attr('class','product-sold-nav');
   } else if(auc.status == 1) {
     $('#bidnav' + auc.id).attr('class','product-suspended-nav');
   } else if(auc.status == 0) {
     $('#bidnav' + auc.id).attr('class','product-bid-nav');
   }
}

var pre_item_ids = null; // an array to hold the auction ID's of the items on the current page, for detecting whether a full page refresh is needed
function is_IDs_same(A,B) {
  // A and B are arrays of integers, check that they are the same, i.e. same length, same elements in the same order
  var len = A.length;
  if(len != B.length) {return false;}
  for(var i=0; i<len; i++) {
    if(A[i] != B[i]) {return false;}
  }
  return true;
}
function need_check_page_refresh(ids) {
  // ids is an array of the current ID's to be shown, check if full page refresh is needed
  if(pre_item_ids == null) {
    pre_item_ids = ids;
    return false;
  }
  return !is_IDs_same(pre_item_ids,ids);
}
function update_top_bidders(top_bidders) {
  // top_bidders is an array, from the latest bidders to earlier bidders
  // each is an array of two items: bidder name, and time
  var len = top_bidders.length;
  if(len > 10) len = 10;
  if(top_bidders[0][0].length <= 0) {len = 0;} // in fact no bidders
  for(var i=0; i<len; i++) {
    $('#lastbid' + i + '_name').html(top_bidders[i][0]);
    $('#lastbid' + i + '_time').html(top_bidders[i][1]);
    $('#lastbid' + i + '_bar').show(0);
  }
  for(var i=len; i<10; i++) {
    $('#lastbid' + i + '_name').html('');
    $('#lastbid' + i + '_time').html('');
    $('#lastbid' + i + '_bar').hide(0);
  }
  if(len <= 0) {$('#ten_top_bid_info').hide(0);} else {$('#ten_top_bid_info').show(0);}
}
function update_auctions_info(response) {
  // the response will be converted to a Javascript object from JSON data
  // the response will be an object with fields:
  //   error: any error message
  //   ret: an array of the information of the auctions
  // update the information on this page accordingly
  var ret = response.ret;
  var len = ret.length;
  var ids = new Array(len);

  for(var i=0; i<len; i++) {
      update_auction(ret[i],i==0);
    ids[i] = ret[i].id;
  }
  // the 10 top bidders
  if(len > 0 && typeof(ret[0].top_bidders)!='undefined') {
    update_top_bidders(ret[0].top_bidders);
  }
  //
  if(need_check_page_refresh(ids)) {location.reload();}
}
var g_refresh_timer = null;
var g_cur_page = 0; // this will be changed suitably
function refresh_auctions_info() {
  // this is used when showing many auctions
  // send ajax request to get info, then update the page
  $.ajax({
    url: "auctions_info.php?page="+g_cur_page ,
    dataType: "json" ,
    success: update_auctions_info
  });
  if(g_refresh_timer) {clearTimeout(g_refresh_timer);}
  g_refresh_timer = setTimeout('refresh_auctions_info()',1000); // 1 second
}

var g_aid = 0; // this will be changed suitably
function refresh_auction_info() {
  // this is used when showing a particular auction
  // send ajax request to get info, then update the page
  $.ajax({
    url: "auction_info.php?aid="+g_aid ,
    dataType: "json" ,
    success: update_auctions_info
  });
  if(g_refresh_timer) {clearTimeout(g_refresh_timer);}
  g_refresh_timer = setTimeout('refresh_auction_info()',1000); // 1 second
}

function bidlink_handler(event) {
  var aid = $(this).attr('id');
  event.preventDefault();
  $.ajax({
	  url: "bid.php",
	  data: {aid:aid},
	  dataType: "json",
	  success: function(response) {
	      var sta = response.status;
	      if(sta == 'OK') {
		  if(g_aid == 0) {refresh_auctions_info();} else {refresh_auction_info();}
		  if(typeof(response.points) != 'undefined') {
		      $('#logged_in_user_bids').html(response.points);
		  }
	      } else if(sta == 'login') { // show the login box
		  gainbid_login();
	      } else if(sta == 'buybid') { // show the buy bid box
	      } else {
		  gainbid_alert(g_bid_err_msg['err'],bid_err_msg[sta]);
	      }
	  },
	  timeout:5000,
	  error: function() {
	      gainbid_alert(g_bid_err_msg['err'],g_bid_err_msg['err']);
          }
      });
}

////////////////////////////////////////////////////////////////////////////////////////

