// CAMA needs error messages in makebid code sorting out
// sort top right auction description- should say public:live

var testmode = false; // set to true to switch off robots and allow multiple bids

// set interval to 2000 and maxbids to 5000 for auction lasting around 11 mins
var DUMMY_BID_INTERVAL = 1000;
var maxbids = 1000; //bids in auc
var bidsperseat = 50;

var bidSpace = new Array();
var uniqueBids = new Array();
var userBids = new Array();
var lub;

var aid;

var leaders;
var lastStatus= new Array();

var userBidCount = 0;

var placedBids = 0;
var removedBids = 0;

var tube = 200; // needs to match tube div

IMAGE_DIR = '../images/';
GRAFIX_DIR = '../grafix/';
ICON_IMAGE_DIR = '/console_images/';

var robotsRunning = testmode; //flag if robots running already

var open = false;

function localAction(data) {
  setTimeout('doLocal("' + data + '")', 200);
}

function doLocal(data) {
  var inp = data.split('|');
  var action = inp[0];
  if (action == 'bid') localModeBid(inp);
  else if (action == 'getinit') getinit(inp);
  else if (action == 'setauct') setauct(inp);
  else if (action == 'getclose') getCloseData(inp);
  else alert('unknown local command ' + action)
}

function getinit(inp) {
  var aid = inp[1];
  parseUpdate( buildConsoleStateMessage(aid, 5) );
}

function setauct(inp) {
  var aid = inp[1];
  updateCaller(aid, 'n', lastStatus);
}

function updateCaller(aid, fresh, status) {
  parseUpdate( buildConsoleSummaryMessage(aid, currentAuction['bidsperseat'], userBidCount, 0) );
  parseUpdate( buildConsoleBidMessage(aid, status, fresh) );
  parseUpdate( buildConsoleFlipsMessage(aid, status) );
  parseUpdate( buildConsoleLeaderMessage(aid) );
  parseUpdate( buildConsoleProgressMessage(aid, maxbids, placedBids, removedBids) );
}

function localModeBid(inp) {
	if (! open && remaining() > 0) {
    open = true;
    var d = new Date();
    currentAuction['start time'] = d;
    displayTime();
  }

  aid = inp[1];
  var bid = inp[2];
  var nickname = inp[3];
  
  if ( remaining() <= 0 ) {
    attemptBid = '';
    displayMessage('this auction is closed, bids are no longer accepted', true);
    return;
  }
  else if ( userBidCount >= currentAuction['bidsperseat'] ) {
    attemptBid = '';
    displayMessage('sorry, you have no more bids remaining', true);
    return;
  }
  else if ( alreadyBid(bid) ) {
    attemptBid = '';
    displayMessage('you have already placed a bid of ' + formatCurrency(bid/100), true);
    if (! testmode) return;
  }
  
  placeBid(bid, nickname);
  
  if ( ! robotsRunning ) {
		setTimeout('placeDummyBids()', DUMMY_BID_INTERVAL);
		robotsRunning = true;
	}
}

function alreadyBid(bid) {
  for (var i=0; i<userBids.length; i++) {
    if ( userBids[i] == bid ) return true;
  }
  return false;
}

function remaining() {
  var remainder = maxbids - placedBids - removedBids;
	if (remainder <= 0 && open) {
    open = false;
    parseUpdate( buildConsoleStateMessage(aid, -1) );
  }
	return remainder;
}

function getCloseData(inp) {
  var aid = inp[1];
  var status = createStatus();
  var winner = leaders[0];
  parseUpdate( buildCloseStateMessage(aid, '', winner, 'Somecity, Somecountry', lub, winner) );
}

function placeBid(bid, nickname) {
  userBidCount++;
  userBids[userBids.length] = bid;
  placeUserBid(bid, nickname);
  var status = createStatus();
  
  updateCaller(aid, 'y', status);
}

var aaa = true;
function placeDummyBids() {
  if (aaa) {
    if ( remaining() > 0 ) removedBids += 2;
    placeUserBid(randomBid(), "robot-01");
    placeUserBid(randomBid(), "robot-02");
    placeUserBid(randomBid(), "robot-03");
    placeUserBid(randomBid(), "robot-04");
    placeUserBid(randomBid(), "robot-05");
    aaa = false;
  }
  else {
    if ( remaining() > 0 ) removedBids += 3;
    placeUserBid(randomBid(), "robot-06");
    placeUserBid(randomBid(), "robot-07");
    placeUserBid(randomBid(), "robot-08");
    placeUserBid(randomBid(), "robot-09");
    placeUserBid(randomBid(), "robot-10");
    aaa = true;
  }

  var status = createStatus();
  updateCaller(aid, 'n', status);

  if ( remaining() > 0 ) setTimeout('placeDummyBids()', DUMMY_BID_INTERVAL);
}

function placeUserBid(bid, user) {
  if ( remaining() <= 0 ) return;
  placedBids ++;
  if (Math.random() > 0.9) removedBids++;
  if (bidSpace[bid] == null) {
    bidSpace[bid] = 1;
    uniqueBids[bid] = user;
  }
  else {
    bidSpace[bid]++;
    delete uniqueBids[bid];
  }
}

function numCmp(a, b) { return a - b; }

function createStatus() {
  lub = Infinity;
  // 1 compute lub and leaders
  var keys = new Array();
  for (var bid in uniqueBids) {
    bid = parseInt(bid);
    keys[keys.length] = bid;
    if ( bid < lub ) lub = bid;
  }
  keys.sort(numCmp);
  leaders = new Array();
  if (lub < Infinity) {
    for (var i=0; i<Math.min(10, keys.length); i++) {
      leaders[i] = uniqueBids[keys[i]];
    }
    //alert (leaders);
  }
  
  // 2 compute status codes
  var status = new Array();
  var bid;
  for (var i=0; i<userBids.length; i++) {
    bid = userBids[i];
    var unique;
    bidSpace[bid] == 1 ? unique = true : unique = false;
    if (lub == Infinity) direction = 0; // no current lowest unique bid
    else if (lub < bid) direction = -1;
    else if (lub > bid) direction = 1;
    else direction = 0;
    
    status[bid] = statusCode(direction, unique);
    
    // needed if simulating queueing mode
    //if (currentAuction['state'] < 5) status[bid] = -1;
  }
  return status;
}

function statusCode(direction, unique) {
  if (direction == 1) { // up
    if (unique) return 3; // error condition
    else return 2;
  }
  else if (direction == -1) { // down
    if (unique) return 5;
    else return 4;
  }
  else {
    if (unique) return 1;
    else return 0;
  }
}

function buildConsoleBidMessage(aid, updates, fresh) {
  var xml = "<upd typ='bidupd' val='" + aid + '|';
	xml += fresh + '|';
  for (var key in updates) {
    xml += key + ',' + updates[key] + '|';
  }
  xml += "' />\n";
  return xml;
}

function buildConsoleLeaderMessage(aid) {
  if (leaders == null) return '';
  var xml = "<upd typ='leaderb' val='" + aid + '|';
  for (var i=0; i<leaders.length; i++) {
    xml += leaders[i] + '|';
  }
  xml += "' />\n";
  return xml;
}

function buildConsoleFlipsMessage(aid, status) {
  var changes = new Array();
  for (var key in lastStatus) {
    if ( lastStatus[key] != status[key] ) {
			var last = lastStatus[key];
			var curr = status[key];
      //only report changes
			if ( last == 0 || last == 1 || last == 5 || curr == 0 || curr == 1 || curr == 5 ) {
        var diff = key;
        if (curr == 1) diff += ',+'; // now LUB
        else if (last == 1) diff += ',-'; // lost LUB
        changes[changes.length] = diff;
      }
		}
  }
  lastStatus = status;
  if (changes.length == 0) return '';
  var xml = "<upd typ='flips' val='" + aid + '|';
  for (var i=0; i<changes.length; i++) {
    xml += changes[i] + '|'
  }
  xml += "' />\n";
  return xml;
}

function buildConsoleProgressMessage(aid, maxbids, placedBids, removedBids) {
  var leftInk = Math.round(placedBids * tube / maxbids);
  var rightInk = Math.round(removedBids * tube / maxbids);
  var xml = "<upd typ='progress' val='0|"; // zero timestamp
  xml += tube + '|' + leftInk + '|' + rightInk; 
  xml += "' />\n";
  return xml;
}

function buildConsoleSummaryMessage(aid, bidsperseat, placedBids, removedBids) {
  var xml = "<upd typ='summary' val='" + aid + '|';
  xml += bidsperseat + '|' + placedBids + '|' + removedBids; 
  xml += "' />\n";
  return xml;
}

function buildConsoleStateMessage(aid, state) {
  var title = 'no lot offered';
  var minbid = 0.01;
  var maxbid = 50;
  image = '../images/circlesim.jpg';

  var xml = "<upd typ='setinit' val='" + aid + '|';
  xml += title + '|0.00|simulation|' + state + '|1|' + minbid + '|' + maxbid + '|' + bidsperseat + '|0|0|0|' + image; 
  xml += "' />\n";
  return xml;
}

function buildCloseStateMessage(aid, first, last, location, lub, nickname) {
  var xml = "<upd typ='closestate' val='" + aid + '|';
  xml += first + '|' + last + '|' + location + '|' + lub + '|' + nickname; 
  xml += "' />\n";
  return xml;
}



