// 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
var lejartazido=false;
// set interval to 2000 and maxbids to 5000 for auction lasting around 11 mins
var DUMMY_BID_INTERVAL = 1600;
var maxbids = 1100; //bids in auc
var bidsperseat = 100;

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 = 'images/';
ICON_IMAGE_DIR = 'images/';

var robotsRunning = testmode; //flag if robots running already

var x_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];
  p2p_parseUpdate( buildConsoleStateMessage(aid, 5) );
}

function setauct(inp) {
  var aid = inp[1];
  updateCaller(aid, 'n', lastStatus);
}

function updateCaller(aid, fresh, status) {
  p2p_parseUpdate( buildConsoleSummaryMessage(aid, currentAuction['bidsperseat'], userBidCount, 0) );
  p2p_parseUpdate( buildConsoleBidMessage(aid, status, fresh) );
  p2p_parseUpdate( buildConsoleFlipsMessage(aid, status) );
  p2p_parseUpdate( buildConsoleLeaderMessage(aid) );
  p2p_parseUpdate( buildConsoleProgressMessage(aid, maxbids, placedBids, removedBids) );
}

function localModeBid(inp) {
	if (! x_open && remaining() > 0) {
    x_open = true;
    var d = new Date();
    currentAuction['start time'] = d;
	
	var Today = new Date();
    var d = new Date(Today.getTime()+300000);

    Todays_Year = d.getFullYear();
    Todays_Month = d.getMonth();	
    countdown_simulator(Todays_Year, Todays_Month+1, d.getDate(), d.getHours(), d.getMinutes(), 0, 1);
	
    displayTime();
  }

  aid = inp[1];
  var bid = inp[2];
  var nickname = inp[3];
  
  if ( remaining() <= 0 ) {
    attemptBid = '';
    displayMessage(_SIM_AUCTIONCLOSED, true);
    return;
  }
  else if ( userBidCount >= currentAuction['bidsperseat'] ) {
    attemptBid = '';
    displayMessage(_SIM_NOMOREBID, true);
    return;
  }
  else if ( alreadyBid(bid) ) {
    attemptBid = '';
    displayMessage(_SIM_YOUPLACEDBEFORE+' (' + 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 && x_open) 
	  {
       x_open = false;
       p2p_parseUpdate( buildConsoleStateMessage(aid, -1) );
      }
	else if (lejartazido)
	        remainder=0;
	return remainder;
}

function getCloseData(inp) {
  var aid = inp[1];
  var status = createStatus();
  var winner = leaders[0];
  p2p_parseUpdate( buildCloseStateMessage(aid, '', winner, '', lub, winner) );
}

function placeBid(bid, nickname) {
  userBidCount++;
  userBids[userBids.length] = bid;
  placeUserBid(bid, nickname);
  var status = createStatus();
  
  updateCaller(aid, 'y', status);
}

var aaa = true;
var firstdummy=true;

function placeDummyBids() {
  var s='';
  s+='lub='+lub+'<br>';
  
  //$('#debug').html(s);
  
  /*if (firstdummy)
   {firstdummy= false;
	placeUserBid(1, "robot-01");
    placeUserBid(2, "robot-02");
    placeUserBid(3, "robot-03");
    placeUserBid(4, "robot-04");
    placeUserBid(5, "robot-05");
	placeUserBid(6, "robot-06");
    placeUserBid(7, "robot-07");
    placeUserBid(8, "robot-08");
    placeUserBid(9, "robot-09");
    placeUserBid(10, "robot-10");
   }*/
  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 = 100;
  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;
}

function randomBid() {
    lmin=lub-100;
	if (lmin<=0) lmin=1;
	lmax=lub+100;
	if (lmax>=10000) lmax=10000;
	return lmin + Math.floor(Math.random() * lmax);
}

function countdown_simulator(year, month, day, hour, minute, time_difference, format)
         {
         var Today = new Date();
         var Todays_Year = Today.getFullYear();
         var Todays_Month = Today.getMonth();

         //Convert today's date and the target date into miliseconds.

         var Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                                 Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
         var Target_Date = (new Date(year, month-1, day, hour, minute, 00)).getTime();

         //Find their difference, and convert that into seconds.
         //Taking into account the time differential between the client computer and the server.
        
		 var Time_Left = Math.round((Target_Date - Todays_Date + time_difference) / 1000);
         //Time_Left = Math.round((Target_Date - time_difference) / 1000);
         var ok=true;
		 if(Time_Left < 0)
           {ok=false;
		    x_open = false;
			lejartazido=true;
            p2p_parseUpdate( buildConsoleStateMessage(aid, -1) );
			p2p_stateChange();
			Time_Left = 0;
		   }
         switch(format)
               {
               case 0:
                    //The simplest way to display the time left.
					bcfrm.document.getElementById( 'countdown' ).innerHTML=Time_Left + ' seconds';
					//$('#countdown').html(Time_Left + ' seconds');
                    break;
               case 1:
                    //More datailed.
                    days = Math.floor(Time_Left / (60 * 60 * 24));
                    Time_Left %= (60 * 60 * 24);
                    hours = Math.floor(Time_Left / (60 * 60));
                    Time_Left %= (60 * 60);
                    minutes = Math.floor(Time_Left / 60);
                    Time_Left %= 60;
                    seconds = Time_Left;

                    dps = 's'; hps = 's'; mps = 's'; sps = 's';
                    //ps is short for plural suffix.
                    if(days == 1) dps ='';
                    if(hours == 1) hps ='';
                    if(minutes == 1) mps ='';
                    if(seconds == 1) sps ='';
					bcfrm.document.getElementById( 'countdown' ).innerHTML=days + ' nap '+pad(''+hours,2,'0') + ':'+ pad(''+minutes,2,'0') + ':'+ pad(''+seconds,2,'0');
					//$('#countdown').html( days + ' nap '+pad(''+hours,2,'0') + ':'+ pad(''+minutes,2,'0') + ':'+ pad(''+seconds,2,'0'));
                    break;
               default:
					bcfrm.document.getElementById( 'countdown' ).innerHTML=Time_Left + ' seconds';
					//$('#countdown').html(Time_Left + ' seconds');
               }

         //Recursive call, keeps the clock ticking.
         if (ok)
		   {
		   setTimeout('countdown_simulator(' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ',' +
                     time_difference + ', ' + format + ');', 1000);
		   }
         }
		 
function startMsg()
{
   $("#dialog2").dialog('option','modal',true);
   $("#dialog2").dialog('option','resizable',false);
   $("#dialog2").dialog('option','width',400);
   $("#dialog2").dialog('option','height',300);
   $("#dialog2").dialog('option','title','Figyelem!');
   $("#dialog2").dialog( { buttons: { "Ok": function() { $(this).dialog("close"); } } } );
   $("#dialog2").dialog().html("<p style=\"color:red;font-size:14px;\">A szimuláció megkezdéséhez tedd meg az első téted!</p>").css({width:"auto", overflowX:"scroll"});
   $("#dialog2").dialog('open');	
}

function close_simulation(txt)
{              $("#dialog").dialog('option','modal',true);
			   $("#dialog").dialog('option','resizable',false);
			   $("#dialog").dialog('option','width',400);
			   $("#dialog").dialog('option','height',200);
			   $("#dialog").dialog('option','title','');
			   $("#dialog").dialog('option','buttons',{"bezárás":function(){$("#dialog").dialog('close');},"Szimuláció újraindítása":function(){window.location.reload();}});
			   $("#dialog").dialog().html(txt).css({width:"auto", overflowX:"scroll"});
			   $("#dialog").dialog('open');
}

