




var DialogBox = Class.create(
{
  buttonOKClick: function(event)
  {
    this.DialogBox.hide();
  },

  pageCreate: function()
  {
  //    this.DialogBox.hide();
      
      this.DialogBox.setStyle({
        height: '100%',
        left: '0px',
        width: '100%',
        top: '0px',
        zIndex: 999
        }
      );
  },

  display: function(msg, caption)
  {
    this.labelCaption.update(caption);
    this.labelDialog.update(msg);
    
    this.DialogBox.show();
    this.buttonOK.activate();
  },

  initialize: function() {

    this.DialogBox = $('DialogBox');
    this.outerBorder = $('outerBorder');
    this.innerBorder = $('innerBorder');
    this.panelDialogClient = $('panelDialogClient');
    this.labelDialog = $('labelDialog');
    this.dialogCaption = $('dialogCaption');
    this.labelCaption = $('labelCaption');
    this.buttonOK = $('buttonOK');
    this.buttonOK.observe('click', this.buttonOKClick.bindAsEventListener(this));
    this.LabelSymbol = $('LabelSymbol');
    this.buttonCancel = $('buttonCancel');
    this.buttonCancel.observe('click', this.buttonOKClick.bindAsEventListener(this));
    try {
      this.pageCreate();
    } catch (e) { }
  }
});

// LiveBidResult
/*
 * 0- 7 : Server
 * 9-15 : Client
 */ 
var LiveBidResult = [
  /*  0 */ 'Your bid was successfully submitted',
  /*  1 */ 'You have just been outbid',
  /*  2 */ 'Sorry you have been outbid',
  /*  3 */ 'You have successfully increased your bid',
  /*  4 */ 'The bid placed was to low, please increase your bid',
  /*  5 */ 'The bid placed is lower or equal to your current maximum bid',
  /*  6 */ 'Failed to lodge bid',
  /*  7 */ '(Enter AU <b>$%d.00</b> or more)',
  /*  8 */ '',
  /*  9 */ '',
  /* 10 */ '(INVALID BID : Enter AU <b>$%d.00</b> or more)',
];


// CountdownTimer Class
/*
 * CountdownTimer constructor
 *
 * contaimer parameter is the name of the html element to update
 *
 * Passed in options
 * {
 *   offsetMinutes: 0 - 59,
 *   starttime: 'June 15, 2009 12:21:00',
 *   endtime: 'June 15, 2009 17:30:00',
 *   baseunit: 'days' / 'hours' / 'minutes' / 'seconds',
 *   debugmode: 'debug',
 *   onupdate: function (),
 *   onexpired: functiom()
 * }
 */
function CountdownTimer(element, options) {
  if (!document.getElementById || !document.getElementById(element)) {
    return;
  }
  
  this.expired = false;
  this.baseunit = options.baseunit || 'days';
  this.debugmode = (typeof options.debugmode != "undefined")? 1 : 0;
  this.element = document.getElementById(element);
  this.endtime = this.parsedate(options.endtime);
  this.offsetMinutes = options.offsetMinutes || 0;
  this.doupdate = options.onupdate || this.onupdate;
  this.doexpired = options.onexpired || this.onexpired;
  
//  this.updateEndtime(options.endtime);
  this.updateServertime(options.starttime);

  // create closure, then assign to simeout - update results every second
  var self = this;   
  this.timeout = setTimeout(function() { self.showresults(); }, 1000);
}


/*
 * CountdownTimer::showresults
 */
CountdownTimer.prototype.showresults = function()
{
  // Disable timer
  clearTimeout(this.timeout);
  
  // difference of endtime and localtime, in seconds
  this.localtime.setSeconds(this.localtime.getSeconds() + 1);
  var timediff = (this.endtime - this.localtime) / 1000;
  this.expired = (timediff < 0);

  var oneMinute = 60;         // minute unit in seconds
  var oneHour = 60*60;        // hour unit in seconds
  var oneDay = 60*60*24;      // day unit in seconds
  var dayfield = Math.floor(timediff/oneDay);
  var hourfield = Math.floor((timediff-dayfield*oneDay)/oneHour);
  var minutefield = Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute);
  var secondfield = Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute));

  // if base unit is hours, set "hourfield" to be topmost level  
  if (this.baseunit == "hours") { 
    hourfield = dayfield * 24 + hourfield;
    dayfield = null;
  }
  
  // if base unit is minutes, set "minutefield" to be topmost level
  else if (this.baseunit == "minutes") {
    minutefield = dayfield * 24 * 60 + hourfield * 60 + minutefield;
    dayfield = hourfield = null;
  }
  
  // if base unit is seconds, set "secondfield" to be topmost level
  else if (this.baseunit=="seconds") {
    var secondfield = timediff;
    dayfield = hourfield = minutefield = null;
  }
  

  // if time has expired call doexpired observer 
  if (this.expired) {
    this.doexpired(dayfield, hourfield, minutefield, secondfield);
  }
  
  // Otherwise call doupdate observer 
  else {   
    this.doupdate(dayfield, hourfield, minutefield, secondfield);
 
    // create closure, then assign to simeout - update results every second
    var self = this;   
    this.timeout = setTimeout(function() { self.showresults(); }, 1000);
  }
}


/*
 * CountdownTimer::onupdate
 *
 * optional parameters
 *  - arguments[0] = days
 *  - arguments[1] = hours
 *  - arguments[2] = minutes
 *  - arguments[3] = seconds
 *
 * Display countdown update
 */
CountdownTimer.prototype.onupdate = function()
{
  var debugstring = (this.debugmode)? "<p style=\"background-color: #FCD6D6; color: black; padding: 5px\"><big>Debug Mode on!</big><br /><b>Current Local time:</b> "+this.localtime.toLocaleString()+"<br />Verify this is the correct current local time, in other words, time zone of count down date.<br /><br /><b>Target Time:</b> "+this.endtime.toLocaleString()+"<br />Verify this is the date/time you wish to count down to (should be a future date).</p>" : "";

  // if target date/time not yet met
  if (this.expired == false) {
    var displaystring =
      ((arguments[0] === null) ? '' : arguments[0] + ' <sup>days</sup> ') +
      ((arguments[1] === null) ? '' : arguments[1] + ' <sup>hours</sup> ') +
      ((arguments[2] === null) ? '' : arguments[2] + ' <sup>minutes</sup> ') +
      ((arguments[3] === null) ? '' : arguments[3] + ' <sup>seconds</sup>');
  }
  
  // else if countdown is expired
  else {
    var displaystring = 'Pre-auction bidding has ended for this lot.';
  }
  
  this.element.innerHTML = debugstring + 
    '<span class="countdown">' + displaystring + '</span>';
}


/*
 * CountdownTimer::onexpired
 *
 * optional parameters
 *  - arguments[0] = days
 *  - arguments[1] = hours
 *  - arguments[2] = minutes
 *  - arguments[3] = seconds
 *
 * Display countdown expired
 */
CountdownTimer.prototype.onexpired = function()
{
  this.element.innerHTML =
    '<span style="color: red">Pre-auction bidding has ended for this lot.</span>';
}
  

/*
 * CountdownTimer::parsedate(timestamp)
 * Date format: '2009-06-17 08:00:00'
 *
 */
CountdownTimer.prototype.parsedate = function(timestamp)
{
  var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1;
  
  y = parseInt(timestamp.substring(0,4), 10); 
  m = parseInt(timestamp.substring(5,7), 10); 
  d = parseInt(timestamp.substring(8,10), 10); 
  h = parseInt(timestamp.substring(11,13), 10); 
  i = parseInt(timestamp.substring(14,16), 10); 
  s = parseInt(timestamp.substring(17,19), 10);
  
  return new Date(y, m, d, h, i, s); 
}


/*
 * CountdownTimer::checkExpired
 */
CountdownTimer.prototype.checkExpired = function()
{
  // if timer had expired and updating the endtime resets this
  // then restart updates
  var timediff = (this.endtime - this.localtime) / 1000;
  this.expired = (timediff < 0);
  
  if (!this.expired) { this.showresults(); }
  return this.expired;
}


/* 
 * CountdownTimer::updateServertime(servertime)
 *
 * servertime parameter is a time stamp of the format: 'YYYY-MM-DD HH:NN:SS'
 */
CountdownTimer.prototype.updateServertime = function(servertime)
{
  if (servertime != null) {
    this.localtime = this.servertime = this.parsedate(servertime);
    // add user offset to server time
    this.localtime.setTime(this.servertime.getTime() + this.offsetMinutes * 60 * 1000);
  }

  this.checkExpired();  
}


/*
 * CountdownTimer::updateEndtime(endtime)
 *
 * endtime parameter is a time stamp of the format: 'YYYY-MM-DD HH:NN:SS'
 */
CountdownTimer.prototype.updateEndtime = function(endtime)
{
  if (endtime != null) { this.endtime = this.parsedate(endtime); }

  this.checkExpired();  
}




// dump
/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
};


// LiveBidStatus
/*
 * 0- 7 : Server
 * 9-15 : Client
 */ 
var bidSUCCESS = 0;
var bidPROXY = 1;
var bidBEATEN = 2;
var bidINCREASE = 3;
var bidTOLOW = 4;
var bidDUPLICATE = 5;
var bidNone = 7;
var bidReserved1 = 8;
var bidReserved2 = 9
var bidINVALID = 10;


// LiveBidResultColor
var LiveBidResultColor = [
  /*  0 */ 'green',
  /*  1 */ 'red',
  /*  2 */ 'red',
  /*  3 */ 'blue',
  /*  4 */ 'red',
  /*  5 */ 'red',
  /*  6 */ 'red',
  /*  7 */ 'black',
  /*  8 */ 'black',
  /*  9 */ 'black',
  /* 10 */ 'red'
];


// LiveBidResultIndicator
var LiveBidResultIndicator = [
  /*  0 */ ' ',
  /*  1 */ '+',
  /*  2 */ '-',
  /*  3 */ '!',
  /*  4 */ '@',
  /*  5 */ '*',
  /*  6 */ '@',
  /*  7 */ ' '
];




var LiveBidURL = 'livebiddialog.php';
var asNone = 0;
var asAuctionStarted = 1;
var asAuctionFinished = 2;
var asLotReady = 3;
var asLotOpened = 4;
var asLotClosed = 5;
var asRoomBid = 6;
var asAbsenteeBid = 7;
var asWebBid = 8;
var asSelling = 9;
var asPassing = 10;
var asStatusMessage = 11;
var LiveBidIndexPage = '../../index.php';
var LiveBidRegisterPage = '../../registerevent/registerevent.php?eventid=';

var LBO = Class.create(
{
  isRegistered: function()
  {
    /*
     * isRegistered: Returns True if the user is Activated & Registered for Event
     */
  if (this.rego !== null) {
    this.clientMessages('isRegisted',
      'LoginName: ' + this.rego.loginname + ',' +
      'Activated: ' + this.rego.activated + ', ' +
      'Registeredid: ' + this.rego.registeredid + '. '
      );
  }
  else {
    this.clientMessages('isRegisted', 'Registration object: ' + this.rego);
  }
    
    var result = (
      (this.rego !== null) &&
      (this.rego.activated !== null) &&
      (this.rego.activated) &&
      (this.rego.registeredid !== null) &&
      (this.rego.registeredid > 0)
      );
  
  //  var result = ((this.rego !== null) && (this.rego.registeredid !== null));
      
    return result;
  },

  placeAbsenteeBid: function()
  {
    /*
     * placeAbsenteeBid: Remote Server Call
     *
     * parameters:
     *   action = name of PHP server method placeWebBid()
     *   bidlotid = lotid for bid being placed
     *
     * Jvr - 14:14:00 03/09/2008
     */
  
    var caller = 'placeAbsenteeBid';
    var parameters;
  
    if ((this.lotid != null) && (this.lotid != '') && (this.lotid  > -1)) {
      parameters = {
        action: caller,
        lotid: this.lotid,
        eventid: this.eventid,
        bidamount: this.editBid.getValue()
        };   
    }
    else {
      parameters = {
        action: caller,
        eventid: this.eventid,
        bidamount: this.editBid.getValue()
        };   
    }
      
    return new Ajax.Request(LiveBidURL, {
      method: 'get',
      parameters: parameters,
      onFailure: function(transport, json) {
        this.clienteMessages(caller, 'Error: Failed to place Bid');
        }.bind(this),
      onSuccess: function(transport, json) {    
        this.serverMessages(caller, transport.responseText);
  this.clientMessages(caller, 'EditBid = "' + $('editBid').getValue()) + '"';
  
        // Process JSON object here!
        if (json !== null) {
          this.resultid = json.resultid;
          
          // Bid was placed, therefore modifed is true
          this.modified = true;
          this.updateBidding(caller);
        }
        else {
          this.clientMessages(caller, 'Warning: Nothing to process');
          alert(dump(json));
        }
        
      }.bind(this)
    });
  },

  checkUserStatus: function()
  {
    /*
     * checkUserStatus: Remote Server Call
     */
  
    var caller = 'checkUserStatus';
    var parameters;
  
    if ((this.stateid != null) && (this.stateid > -1)) {
      parameters = { action: caller, stateid: this.stateid };   
    }
    else {
      parameters = { action: caller };   
    }
    
    return new Ajax.Request(LiveBidURL, {
      method: 'get',
      parameters: parameters,
      onSuccess: function(transport, json) {     
        this.serverMessages(caller, transport.responseText);
  
        // Update the registration information from the server json object
        this.rego = json;
        
        // Process rego object here!
        if (this.rego !== null) {     
  /*  
  this.clientMessages(caller,
    'LoginName: ' + this.rego.loginname + ',' +
    'Activated: ' + this.rego.activated + ', ' +
    'Registeredid: ' + this.rego.registeredid + '. '
    );
  */
  
          if (this.rego.stateid !== null) {
            this.stateid = this.rego.stateid;
          }
          else {
            this.stateid = 0;
          }
  
          if (this.stateid > 0) {
            $('LiveBidDialog').show();
          }
          else {
            $('LiveBidDialog').hide();
          }
        
          // Login                     
          this.updateLogin((this.rego.loginname !== null), this.rego.loginname);
  
          // Bidding and Registered Status            
          this.updateUserStatus(
            (this.rego.activated !== null) && (this.rego.activated === true),
            (this.rego.registeredid)
            );
        }
          
        // No data was returned, user is mot logged in
        else {
          this.updateLogin(false, '');
          this.updateUserStatus(false, null);
        }
                       
        // Registered for current auction - Enable / Disable Bid Button
        this.updateBidButton();
        
  this.clientMessages(caller, 'SUCCESS');
      }.bind(this)
    });
  },

  periodicalRefresh: function(interval)
  {
    /*
     * periodicalRefresh: updates the screen periodically
     *
     * 07/02/2007 8:11:00
     * Added Queing of updates to regulate the screen refresh based on the user
     * browser response time (Throtteling)
     *
     * The "this.queueOffset" variable regulates the through-put
     */
    var caller = 'periodicalRefresh';
    
    this.updateBidding(caller);
  
    // Initialise the timer
    this.timer = new PeriodicalExecuter(function() {
      // Only refresh if the LiveBidOnline Dialog is open
      if (this.stateid > 0) {
        this.updateBidding(caller);
      }
    }.bind(this), interval);
  },

  updateScreen: function()
  {
    /* Purpose: processes the json response object passed in
     * Jvr - 12:33:00 11/09/2008
     */
    var caller = 'updateScreen';
    this.clientMessages(caller, '>>>>>>');
    
    if (this.stateid > -1) {
      this.checkUserStatus();
      this.updateLot();
      this.updateImage(false);
      this.updateAsking();
    
      if (this.modified === true) {
        this.updateBiddingSteps();
        this.modified = false;
      }
  
      this.updateAmount();
      this.updateHistory();
    }
  },

  updateMessage: function(msg)
  {
    /*
     * updateMessage: displays message in message area
     */
     
    if ((msg !== null) && (msg !== '')){
      this.panelMessage.insert('Message(s): (' + msg + ')<br />');
    }
  
  /*
    var comment;
      
    if ((msg === null) || (msg === '')){
      comment = DefaultStatusMessage;
    }
    else {
      comment = msg;
    }
  
    var crc = strCRC8(comment);
    if (crc !== this.crc) {
      this.PanelBidMessage.update(comment);
    }
      
    // Update the Message checksum
    this.crc = crc;
  */
  },

  updateSummary: function(msg)
  {
    /*
     * updateSumary: displays the user bids
     * Jvr - 09:08:00 11/09/2008
     */
     
    var caller = 'updateSummary'; 
    var parameters = {
      action: 'getSummary',
      eventid: this.eventid
      };
  
  this.clientMessages(caller, 'CALLED FROM: ' + msg);
    return new Ajax.Request(LiveBidURL, {
      method: 'get',
      parameters: parameters,
      onFailure: function(transport, json) {
        this.clientMessages(caller, 'Failed to update summary');
        }.bind(this),
      onSuccess: function(transport, json) {
        this.serverMessages(caller, transport.responseText);
  
        if (json !== null) {
  //        var livelot = $A(json).compact();
          var absenteebids = '';        
  //        var absenteebids = '<table class="absenteebids" id="tableAbsentee" border="0" width="98%"><tbody>';
              
          $A(json).compact().each(
            function(row) {
              if (row !== null) {
  /*
                var bidamount = (row.bidderid == this.bidderid) ? row.maximum : row.actual;
                var status = (row.bidderid == this.bidderid) ? 'You are the high bidder' : 'You have been outbid';
                var statuscell = (row.bidderid == this.bidderid) ? '<td class="highbid">' : '<td class="outbid">';
                if (row.bidderid < 1000) {
                  row.bidderid = '**';
                }
  */
                var bidamount = (row.bidderid > -1) ? row.maximum : row.actual;
                var status = (row.bidderid > -1) ? 'You are the high bidder' : 'You have been outbid';
                var statuscell = (row.bidderid > -1) ? '<td class="highbid">' : '<td class="outbid">';
                if (row.bidderid < 1000) {
                  row.bidderid = '**';
                }
  
                absenteebids +=
                  '<tr id="' + row.lotid +'">' +
                  '<td>' + row.lotid + '</td>' +
                  '<td>' + row.bidderid + '</td>' +
                  '<td>AU $' + bidamount + '</td>' +
                  '<td>AU $' + row.actual + '</td>' +
                  '<td>AU $' + row.asking + '</td>' +
                  '<td>' + row.bidcount + '</td>' +
                  '<td>' + row.created + '</td>' +
                  statuscell + status + '</td>' +
                  '</tr>';
                  
                }
              }
            );
                      
  //        absenteebids += '</tbody></table>';
          
  //##OLD        $('dataSummary').update(absenteebids); 
          $('tableSummary-data').update(absenteebids); 
          this.clientMessages(caller, 'SUCCESS');
        }
          
        else {
  //##OLD        $('dataSummary').update(
          $('tableSummary-data').update(
            '<tr id="0" clospan=7>  <td class="ok"><b>NO DATA</b></td></tr>'
          );
          this.clientMessages(caller, 'Nothing to process');
        }
  
  
  /*
          // iterate the records and format the data
          foreach($data as $key => $row) {
            $bidamount = ($row['bidderid'] == $this->bidderid) ? $row['maximum'] : $row['actual'];
            $status = ($row['bidderid'] == $this->bidderid) ? 'You are the high bidder' : 'You have been outbid';
            $statuscell = ($row['bidderid'] == $this->bidderid) ? '<td class="highbid">' : '<td class="outbid">';
            if ($row['bidderid'] < 1000) {
              $row['bidderid'] = '**';
            }
            
            $biddata[$key] = '<tr id="'.$row['lotid'].'">'.
              '<td>'.$row['lotid'].'</td>'.
              '<td>'.$row['bidderid'].'</td>'.
              '<td>AU $'.$bidamount.'</td>'.
              '<td>AU $'.$row['actual'].'</td>'.
              '<td>AU $'.$row['asking'].'</td>'.
              '<td>'.$row['bidcount'].'</td>'.
              '<td>'.$row['created'].'</td>'.
              $statuscell.$status.'</td>'.
              '</tr>';        
          }
  */
  /*
        // Process JSON object here!
        if (json !== null) {
          $('dataSummary').update('');
          
          for (var index = 0; index < json.length; ++index) {
            $('dataSummary').insert(json[index]);
          }
        }
        else {
          $('dataSummary').update(
            '<tr id="0" clospan=7>  <td class="ok"><b>NO DATA</b></td></tr>'
          );
        }
  */
        // Setup odd and even rows  
        $$('table tbody > tr:nth-child(odd)').each(
          function(element) { element.addClassName('odd'); }
          );
  
        // Set up even rows    
        $$('table tbody > tr:nth-child(even)').each(
          function(element) { element.addClassName('even'); }
          );
  
  this.clientMessages(caller, 'SUCCESS');
      }.bind(this)
    });
  
  },

  updateBidding: function(msg)
  {
    /*
     * 27/05/2008 13:50:00
     * updateBidding: Remote Method Call
     *
     */
  
    var caller = 'updateBidding';
    var parameters;
  
    if ((this.lotid != null) && (this.lotid != '') && (this.lotid  > -1)) {
      parameters = {
        action: 'getBidView',
        lotid: this.lotid,
        eventid: this.eventid
        };   
    }
    else {
      parameters = {
        action: 'getBidView',
        eventid: this.eventid
        };         
    }
    
  
  this.clientMessages(caller, 'CALLED FROM: ' + msg);
    return new Ajax.Request(LiveBidURL, {
      method: 'get',
      parameters: parameters,
      onFailure: function(transport, json) {
        this.clientMessages(caller, 'Error: Failed to get Lot details');
        }.bind(this),
      onSuccess: function(transport, json) {
        this.serverMessages(caller, transport.responseText);
  
        // Process JSON object here!
        if (json !== null) {
          this.json = json;
  
          // if assigned then update lotid
          if ((json.lotid !== null) && (json.lotid !== '') && (json.lotid > -1)) {
            this.lotid = json.lotid;
          }
  
          // if assigned then update lastid
          if ((json.lastid !== null) && (json.lastid !== '') && (json.lastid > -1)) {
            this.lastid = json.lastid;
          }
  
  
  // Only update the catalogue fields if placeAbsenteeBid is the caller
  if (msg == 'placeAbsenteeBid') {        
      // Update the web catalogue page  
      var fieldMinimumBid = $('asking' + this.lotid);
      if (fieldMinimumBid !== null) { 
        fieldMinimumBid.update('$' + this.json.asking);
        fieldMinimumBid.addClassName('lotbid');
      }
      var fieldHighBidder = $('high' + this.lotid);
      if (fieldHighBidder !== null) { 
        fieldHighBidder.update('High Bidder: ' + this.json.bidderid);
      }
  }
  
       
          // Update the contents
          this.updateScreen();
              
          // Update last object for comparison next iteration
          this.last = json;        
        }
        else {
          // if json is unassigned then restore lotid
          if ((this.lastid !== null) && (this.lastid !== '') && (this.lastid > -1)) {
            this.lotid = this.lastid;
          }
  
          // Update the contents
          this.updateScreen();
        }
          
  this.clientMessages(caller, 'SUCCESS');
      }.bind(this)
    });
  
  },

  updateBiddingSteps: function()
  {
    /* Purpose: Remote Method Call to update bidding steps dropdown box
     * Jvr - 27/05/2008 13:50:00
     *
     * parameters:
     *   action = name of PHP server method getBiddingSteps()
     */
  
    var caller = 'getBiddingSteps';
    if (this.json !== null) {
      var asking = this.json.asking;
    }
    else {
      var asking = 0;
    }
    
    var parameters = {
      action: 'getBiddingSteps',
      asking: asking,
      bidstepcount: 50
      };
  
    return new Ajax.Request(LiveBidURL, {
      method: 'get',
      parameters: parameters,
      onFailure: function(transport, json) {
        this.clientMessages(caller, 'Error: Failed to get Bidding Steps');
        }.bind(this),
      onSuccess: function(transport, json) {
        this.serverMessages(caller, transport.responseText);
  
        // Process JSON object here!
        if (json !== null) {     
          element = '<select id="editBid" name="editBid"><option></option>';
          $A(json).compact().each(
            function(row) {
              if (row !== null) {
                element += '<option>' + row.result + '</option>'
                }
              }
            );
  
          element += '</select>';
          this.editBid.replace(element);
            
          /* Update the reference */
          this.editBid = $('editBid');
        }
        else {
          this.clientMessages(caller, 'Warning: Nothing to process');
        }
          
      }.bind(this)
    });
  }
  ,

  updateLot: function()
  {
    /*
     * updateLot: Updates the eventid only when required
     */
  
    var tmpheading = '';
  
    var isValidStatus = (
      (this.json !== null) && (
        (this.last === null) ||
        (this.last.lotid === null) ||
        (this.json.lotid !== this.last.lotid)
        )
      );
  
    if (isValidStatus) {
      // Update EventID
      if (this.json.eventid !== null) {
        this.fieldEventID.update(this.json.eventid);
  //EVENTID      this.fieldSummaryID.update(this.json.eventid);
      }
  
      // Update LotID
      if (this.json.lotid !== null) {
        this.fieldLotID.update(this.json.lotid);
      }
      
      // Update Lot Heading (section)
      if (this.json.lotsectionheading !== null) {
        tmpheading = this.json.lotsectionheading;
      }
  
      // Update Lot Heading (code)
      if (this.json.lotcodeheading !== null) {
        tmpheading += ' - ' + this.json.lotcodeheading;
      }
  
      // Update combined Heading    
      this.labelLotHeading.update(tmpheading);
  
      // Update Lot Description
      if (this.json.description !== null) {
        this.panelLotDescription.update(this.json.description);
      }
  
      // Update Lot Estimate
      if (this.json.estimate !== null) {
        this.fieldEstimate.update('$'+this.json.estimate);
      }
    }
  },

  updateHistory: function()
  {
    /*
     * 02/06/2009 12:03:00
     * updateHistory: Remote Method Call
     *
     * parameters:
     *   action = name of PHP server method getBidHistory()
     *
     */
  
    var caller = 'updateHistory';
    var parameters;
  
    if ((this.lotid != null) && (this.lotid != '') && (this.lotid  > -1)) {
      parameters = {
        action: 'getBidHistory',
        lotid: this.lotid,
        lastid: this.lotid,
        eventid: this.eventid
        };
    }
    else {
      parameters = {
        action: 'getBidHistory',
        eventid: this.eventid
        };
    }
    
    return new Ajax.Request(LiveBidURL, {
      method: 'get',
      parameters: parameters,
      onFailure: function(transport, json) {
        this.clientMessages(caller, 'Error: Failed to get History Details');
        }.bind(this),
      onSuccess: function(transport, json) {
        this.serverMessages(caller, transport.responseText);
  
        // Process JSON object here!
        if (json !== null) {
          var bidhistory = '';
          $A(json).compact().each(
            function(row) {
              if (row !== null) {
                if (row.bidderid < 1000) {
                  var highbidderid = '**';
                }
                else {
                  var highbidderid = row.bidderid;
                }
                        
                bidhistory = bidhistory + '<tr> ' +
                  '<td>' + highbidderid + '</td>' +
                  '<td> AU $' + row.actual + '</td>' +
                  '<td>' + row.created + '</td>' +
                  '</tr>';
              }
            }
          );
          
          this.clientMessages(caller, 'SUCCESS');
        }
        else {
          this.clientMessages(caller, 'Warning: Nothing to process');
        }
  
        // Ok now reresh the bid history
        $('gridHistory-data').update(bidhistory);
      }.bind(this)
    });
  },

  updateImage: function(refresh)
  {
    /*
     * updateImage: Updates the eventid only when required
     * 30/05/2008 11:38:00
     */
  
    var isValidStatus = (
      (this.json !== null) && (
        (refresh === true) ||
        (this.last === null) ||
        (this.last.lotid === null) ||
        (this.json.lotid !== this.last.lotid)
        )
      );
  
    // Only update if status is LotReady or a full refresh is required
    if (isValidStatus) {
      if (this.json.imagename === null) {
        this.panelImage.update('Live<br/>Bid<br/>Online');
      }
      else {
        this.panelImage.update('<img src="' + this.json.imagename + '" /> ');
      }
    }
  },

  updateAsking: function()
  {
    /*
     * updateAsking: Updates the asking amount only when required
     *
     * 27/03/2008 17:55:23 - added check for asPassing to display asking amount
     * 30/05/2008 11:52:00
     */
  
    var asking = 0;
    
    var isValidStatus = (
      (this.json !== null) &&
      (this.json.asking !== null)
      );
  
    if (isValidStatus) {
      asking = this.json.asking;
  
      // Update asking amount
  /*    
      if (this.resultid === bidNone) {
        this.fieldSuggest.update('(Enter AU <b>$' + asking + '.00</b> or more)');
      }
      else {
        this.fieldSuggest.update(LiveBidResult[this.resultid]);
      }
  */
      this.fieldSuggest.update(LiveBidResult[this.resultid].replace('%d', asking));
      this.fieldSuggest.setStyle({ color: LiveBidResultColor[this.resultid] });
      
      this.fieldAsking.update('$' + asking + '.00');
      
      this.fieldSuggest.show();
      this.fieldAsking.show();
      this.labelAsking.show();
    }
    else {
      this.fieldSuggest.hide();
      this.fieldAsking.hide();
      this.labelAsking.hide();
    }
  },

  updateAmount: function()
  {
    /*
     * updateAmount: Updates the bid amount only when required
     *
     * 27/03/2008 15:06:34 - updated 'isValidStatus' to exclude asPassing
     */
  
    var isValidStatus = (
      (this.json !== null) &&
      (this.json.bid !== null) &&
      (this.json.bid > 0)
      );
  
    // Update bid amount
    if (isValidStatus) {
      this.fieldBidAmount.update("$" + this.json.bid + '.00');
      this.fieldBidAmount.show();
      this.labelBidAmount.show();
      
      this.fieldBidderID.update(this.json.bidderid);
      this.fieldBidderID.show();
      this.labelBidderID.show();
    }
    else {
      this.fieldBidAmount.hide();
      this.labelBidAmount.hide();
      
      this.fieldBidderID.hide();
      this.labelBidderID.hide();
    }
  },

  updateBidButton: function()
  {
    /*
     * updateBidButton: enable / disable bid button
     *
     * 27/03/2008 14:12:12 - added asPassing State
     * 30/05/2008 11:15:00
     */
  
    // Registered for current auction - Enable / Disable Bid Button
    var caller = 'updateBidButton';
  this.clientMessages(caller, 'Calling: isRegistered()');
  
    var allowBidding = this.isRegistered(); 
  this.clientMessages(caller, 'allowBidding: ' + allowBidding);
  
    // Disable the button and summary tab
    this.buttonBid.disabled = ((!allowBidding) || ((this.countdown.expired) && (this.admin == false)));
    this.tabSummary.disabled = !allowBidding; 
  this.clientMessages(caller, 'Admin = ' + this.admin + ', buttonBid.disabled = ' + this.buttonBid.disabled);
    
    // Now display the button and summary tab as disabled with CSS
  //  if ((allowBidding) && (!this.countdown.expired)) {
    if (!this.buttonBid.disabled) {
  //    alert('ok' + this.countdown.expired);
      this.buttonBid.className = 'buttonenabled';
    }
    else {
  //    alert('expired' + this.countdown.expired);
      this.buttonBid.className = 'buttondisabled';
    }
    
  //  if (allowBidding) {
    if (!this.buttonBid.disabled) {
      this.tabSummary.className = 'buttonenabled';
    }
    else {
      this.tabSummary.className = 'buttondisabled';
    }
  }   ,

  updateLogin: function(auctionid, username)
  {
    /*
     * updateLogin: update Login details based on if the user is logged in or not
     */
  
    var caller = 'updateLogin';
    
    if (auctionid) {
      this.tabsheetLogin.hide();
      this.tabsheetUserStatus.show();
      
      this.fieldLogin.update('Logged in as: ' + username);
      this.labelLogin.update('&nbsp;&bull;&nbsp; Live Bidding Status:&nbsp;');
      this.labelMyAccount.update(
        '&nbsp;&bull;&nbsp; <a href="' + LiveBidIndexPage + '">Return to My Account</a>');
  //      '&nbsp;&bull;&nbsp;Return to <a href="' + LiveBidIndexPage + '">MyAccount</a>');
    }
    else {
      this.tabsheetUserStatus.hide();
      this.tabsheetLogin.show();
      
      this.fieldLogin.update('Not logged in');
      this.labelLogin.update('Please <a href="' + LiveBidIndexPage + '">click here</a> to login.');
      this.labelMyAccount.update('');
    }
  },

  updateUserStatus: function(activated, registeredid)
  {
    /*
     * updateUserStatus: enable /disable bid button
     */
     
    var caller = 'updateUserStatus';
     
    // Update Activated
    if (activated) {
      this.fieldActivated.update('Active');
      this.fieldActivated.className = 'active';
  
      this.labelRegistered.update('&nbsp;&bull;&nbsp;Bidder ID:&nbsp;');
      this.fieldRegistered.show();
    }
    else {
      this.fieldActivated.update('Inactive');
      this.fieldActivated.className = 'inactive';
  
      this.labelRegistered.update('');
      this.fieldRegistered.hide();
    }
  
    // Update Registered    
    if (activated) {
      if (registeredid != null) {
        this.labelRegistered.update('&nbsp;&bull;&nbsp; Bidder ID:&nbsp;');
        this.fieldRegistered.update(registeredid);
        this.fieldRegistered.className = 'active';
      }
      else {
  //      this.labelRegistered.update('&nbsp;&bull;&nbsp;Please <a href="' + LiveBidRegisterPage + this.eventid + '">Register for this Event</a>');
        this.labelRegistered.update('&nbsp;&bull;&nbsp; <a href="' + LiveBidRegisterPage + this.eventid + '">Register for this Event</a>');
        this.fieldRegistered.update('Not Registered');
        this.fieldRegistered.className = 'inactive';
      }
    }
    
    // Update Lot EndTime
    if ((this.json !== null) && (this.json.endtime !== null)) {
  this.clientMessages(caller, 'Calling: this.countdown.updateEndtime(this.json.endtime)');
      this.fieldEndtime.update(this.json.endtime);
      this.countdown.updateEndtime(this.json.endtime);
      this.countdown.updateServertime(this.json.now);
    }   
  },

  loginFailure: function(msg)
  {
    alert('The login information you provided is invalid.\n\nPlease enter your username and password.');
  },

  tabSummaryClick: function(event)
  {
    var caller = 'tabSummaryClick';
      
  //  this.checkUserStatus();
  this.updateBidding(caller);
  
    if (this.isRegistered()) {
      this.updateSummary(caller);
      this.pageSummary.show(); 
      this.pageBidding.hide();
    }
  },

  tabBiddingClick: function(event)
  {
    var caller = 'tabBiddingClick';
  
    // Force full update  
    this.modified = true;
    this.updateBidding(caller);
    
    this.pageBidding.show();
    this.pageSummary.hide();
  },

  buttonBidClick: function(event)
  {
    /* Purpose: initiates the placing of a bid
     * Jvr - 02/09/2008 12:22:00 - Initial release
     * Jvr - 29/10/2009 12:08:00 - Fixed refresh of fieldSuggest
     */
     
    if ((this.json !== null) && (this.json.asking !== null)) {
      if (this.editBid.getValue() < this.json.asking) {
        this.resultid = bidINVALID;
        this.updateAsking();
      }
      else {
        var msg = 'Place a bid of AU $' +
          this.editBid.getValue() + ' for Lot #' + this.fieldLotID.innerHTML + ' ?';
          
        this.dialogBox.display(msg, 'Submit Bid!');    
      }
    }
  },

  buttonConfirmClick: function(event)
  { 
    this.placeAbsenteeBid();
  },

  buttonPriorClick: function(event)
  {
    this.displayLot(this.eventid, this.lotid-1, this.admin);
  },

  pageSummaryClick: function(event)
  {
    var caller = 'pageSummaryClick';
    var element = event.findElement('tbody tr');
    
    if (element) {
      event.stop();
      elenent = $(element);
      
      this.lotid = +element.identify();
      this.checkUserStatus();
      this.updateBidding(caller);
    
      // Make the bidding page visible  
      this.pageSummary.hide(); 
      this.pageBidding.show();
    }
  this.clientMessages(caller, 'SUCCESS');
  },

  pageCreate: function()
  {
    var caller = 'pageCreate';
  this.clientMessages(caller, '-->-->-->');
    
    // Setup the dialog box
    this.dialogBox = new DialogBox();
  
    // Hide all pages of pageControlLogin
    this.tabsheetLogin.hide();
    this.tabsheetUserStatus.hide();
      
    // Hide all other pageControl pages
    this.pageSummary.hide();
  
    // Get Parameters from Url
    id = this.getUrlParam('eventid');
    if (id != null) {
      this.eventid = id;
    }
    
    id = this.getUrlParam('lotid');
    if (id != null) {
      this.lotid = id;
    }
  
    // Setup Ok button on confirmation dialogbox
    Event.observe('buttonOK', 'click', this.buttonConfirmClick.bindAsEventListener(this));
  
    // Setup spinner
    Ajax.Responders.register({
      onCreate: function() { $('spinner').show(); },
      onComplete: function() {
        if (Ajax.activeRequestCount == 0) { $('spinner').hide(); }
      }
    });
  
    // Setup Counter
    this.countdown = new CountdownTimer(
      'fieldCounter',
      { starttime: '2009-01-01 00:00:00', endtime: '2009-06-01 00:00:00' }
    );
    
    // Check user status + Get Data
    if (this.stateid > -1) {
      this.checkUserStatus();
    }
    
    // Setup periodic refresh of 30 seconds
    this.periodicalRefresh(this.refreshInterval);
        
  this.clientMessages(caller, '<--<--<--');
  },

  getUrlParam: function(paramName)
  {
    paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]" + paramName + "=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return results[1];
  },

  buttonLoginClick: function(event)
  {
    /*
     * buttonLoginClick: allows user to login
     *
     * Jvr - 09:27:00 09/09/2008
     */
  
    var caller = 'buttonLoginClick';
    var authname = this.editUsername.getValue();
    var authpasswd = this.editPassword.getValue();
    
    if (this.pageSummary.visible()) {
      var pageindex = 0;
    }
    else {
      var pageindex = 1;
    }
    
    var parameters = {
      action: 'login',
      username: authname,
      password: authpasswd,
      pageindex: pageindex
      };
  
    if (authname == '') {
      this.loginFailure();
    }
    else {
      return new Ajax.Request(LiveBidURL, {
        method: 'get',
        parameters: parameters,
        onFailure: function(transport, json) {
          this.clientMessages(caller, 'Failed to login');
          }.bind(this),
        
        onSuccess: function(transport, json) {
          this.serverMessages(caller, transport.responseText);
  
          // Process JSON object here!
          if (json !== null) {
            this.json = json;
  
            if (this.json.authstatus == -3) {
              this.loginFailure();
            }
            else if (this.json.authstatus != '') {
              alert('Unknown error status = ' + this.json.authstatus);
            }
            
            // Update the contents
            this.checkUserStatus();
            if (this.pageSummary.visible()) {
              this.updateSummary(caller);
            }
            else {
              this.resultid = bidNone;
              
              // Force full Update
              this.modified = true;
              this.updateBidding(caller);
            }
    
            // Update last object for comparison next iteration
            this.last = json;        
          }
          else {
            this.clientMessages(caller, 'Warning: Nothing to process');
          }
    
  this.clientMessages(caller, 'SUCCESS');       
        }.bind(this)
      });
    }
  },

  buttonLogoutClick: function(event)
  {
    /*
     * buttonLogoutClick: allows user to logout
     *
     * Jvr - 10:13:00 09/09/2008
     */
  
    var caller = 'buttonLogoutClick';
    
    var parameters = {
      action: 'logout'
      };
  
    return new Ajax.Request(LiveBidURL, {
      method: 'get',
      parameters: parameters,
      onFailure: function(transport, json) {
        this.clientMessages(caller, 'Failed to logout');
        }.bind(this),
        
      onSuccess: function(transport, json) {
        this.serverMessages(caller, transport.responseText);
  
        // Process JSON object here!
        if (json !== null) {
          this.json = json;
  
          // Update the contents
          this.checkUserStatus();
    
          this.resultid = bidNone;
          
          // Force full Update
          this.modified = true;
          this.updateBidding(caller);
    
          this.pageBidding.show();
          this.pageSummary.hide();
  
          // Update last object for comparison next iteration
          this.last = json;        
        }
        else {
          this.clientMessages(caller, 'Warning: Nothing to process');
        }
          
  this.clientMessages(caller, 'SUCCESS');
      }.bind(this)
    });
  },

  clientMessages: function(caller, msg)
  {
    /*
     * clientMessages: displays client messages in console
     * Jvr - 08:29:00 11/09/2008
     */
  
    if ((this.debugid > 0) && (window.console)) {     
      if ((msg != null) && (caller != null)) {
        console.info('CLIENT::' + caller + ' (' + msg + ')');
      }
      else {
        console.error('clientMessages (bad args');
      }
    }
  },

  serverMessages: function(caller, msg)
  {
    /*
     * serverMessages: displays server messages in console
     * Jvr - 08:29:00 21/09/2008
     */
  
    if (window.console) {     
      if ((msg != null) && (caller != null)) {
        if (msg != '') {
          console.warn('SERVER::' + caller + ' (');
          msg.split('|').each(function(s) { if (s != '') { console.warn('  ' + s); } });
          console.warn('  )');
        }
      }
      else {
        console.error('serverMessages (bad args');
      }
    }
  },

  buttonCloseClick: function(event)
  {
    this.stateid = 0;
    $('LiveBidDialog').hide();
    $('content').removeClassName('LiveBidDialog');
    
    this.checkUserStatus();
  },

  displayLot: function(eventid, lotid, pagecode, admin)
  {
    /* Purpose: display specified lot
     *
     * Jvr - 29/08/2009 06:18:11 - this is called from the catalogue screen
     */
    var caller = 'displayLot';
  
    // Force full update  
    this.modified = true;
    
    this.eventid = eventid;
    this.lotid = lotid;
    this.admin = admin;
    this.resultid = bidNone;
    this.stateid = 1;  
    this.pagecode = pagecode;
    
    // Counter field only needs to be displayed for custoners
    if (this.admin == true) {
      this.fieldCounter.hide();
    }
    else {
      this.fieldCounter.show();
    } 
  
    $('content').addClassName('LiveBidDialog');
    
    this.checkUserStatus();
    
  //  this.tabBiddingClick();
    this.updateBidding(caller);
  this.clientMessages(caller, 'Admin = ' + this.admin);
  },

  buttonNextClick: function(event)
  {
    this.displayLot(this.eventid, this.lotid+1, this.admin);
  },

  initialize: function() {
    this.debugid= 10;
    this.statusid= asNone;
    this.lotid= -1;
    this.crc= 0;
    this.rego= null;
    this.json= null;
    this.last= null;
    this.eventid= 326;
    this.resultid= bidNone;
    this.stateid= -1;
    this.pagecode= '';
    this.lastid= null;
    this.modified= true;
    this.refreshInterval= 3;
    this.admin= false;

    this.LBO = $('LBO');
    this.caption = $('caption');
    this.product = $('product');
    this.fieldLogin = $('fieldLogin');
    this.buttonClose = $('buttonClose');
    this.buttonClose.observe('click', this.buttonCloseClick.bindAsEventListener(this));
    this.Spacer = $('Spacer');
    this.client = $('client');
    this.pageControlStatus = $('pageControlStatus');
    this.tabsheetUserStatus = $('tabsheetUserStatus');
    this.labelLogin = $('labelLogin');
    this.fieldActivated = $('fieldActivated');
    this.labelRegistered = $('labelRegistered');
    this.fieldRegistered = $('fieldRegistered');
    this.labelMyAccount = $('labelMyAccount');
    this.labelMyAccount.observe('click', this.buttonCloseClick.bindAsEventListener(this));
    this.labelLogout = $('labelLogout');
    this.labelLogout.observe('click', this.buttonLogoutClick.bindAsEventListener(this));
    this.tabsheetLogin = $('tabsheetLogin');

    this.labelUsername = $('labelUsername');
    this.editUsername = $('editUsername');
    this.labelPassword = $('labelPassword');
    this.editPassword = $('editPassword');
    this.buttonLogin = $('buttonLogin');
    this.buttonLogin.observe('click', this.buttonLoginClick.bindAsEventListener(this));
    this.labelRegister = $('labelRegister');
    this.labelRegister.observe('click', this.buttonCloseClick.bindAsEventListener(this));
    this.panelMessage = $('panelMessage');
    this.textInfo = $('textInfo');

    this.PageControl = $('PageControl');
    this.pageSummary = $('pageSummary');
    this.pageSummary.observe('click', this.pageSummaryClick.bindAsEventListener(this));
    this.headerSummary = $('headerSummary');
    this.Label2 = $('Label2');
    this.Label3 = $('Label3');
    this.panelMyBids = $('panelMyBids');
    this.indicatorSummary = $('indicatorSummary');
    this.tableSummary = $('tableSummary');
    this.pageBidding = $('pageBidding');
    this.header1 = $('header1');
    this.labelEventID = $('labelEventID');
    this.fieldEventID = $('fieldEventID');
    this.labelLotHeading = $('labelLotHeading');
    this.labelLotID = $('labelLotID');
    this.fieldLotID = $('fieldLotID');
    this.labelEstimate = $('labelEstimate');
    this.fieldEstimate = $('fieldEstimate');
    this.labelBidderID = $('labelBidderID');
    this.fieldBidderID = $('fieldBidderID');
    this.section1 = $('section1');
    this.panelImage = $('panelImage');
    this.buttonPrior = $('buttonPrior');
    this.buttonPrior.observe('click', this.buttonPriorClick.bindAsEventListener(this));
    this.buttonNext = $('buttonNext');
    this.buttonNext.observe('click', this.buttonNextClick.bindAsEventListener(this));
    this.panelLotDescription = $('panelLotDescription');
    this.info2 = $('info2');
    this.labelBidAmount = $('labelBidAmount');
    this.fieldBidAmount = $('fieldBidAmount');
    this.info3 = $('info3');
    this.labelAsking = $('labelAsking');
    this.fieldAsking = $('fieldAsking');
    this.panelFooter = $('panelFooter');
    this.Label1 = $('Label1');
    this.LabelAU = $('LabelAU');
    this.editBid = $('editBid');
    this.fieldSuggest = $('fieldSuggest');
    this.buttonBid = $('buttonBid');
    this.buttonBid.observe('click', this.buttonBidClick.bindAsEventListener(this));
    this.fieldEndtime = $('fieldEndtime');
    this.labelEndtime = $('labelEndtime');
    this.fieldCounter = $('fieldCounter');
    this.indicatorBidding = $('indicatorBidding');
    this.gridHistory = $('gridHistory');
    this.tabSummary = $('tabSummary');
    this.tabSummary.observe('click', this.tabSummaryClick.bindAsEventListener(this));
    this.tabBidding = $('tabBidding');
    this.tabBidding.observe('click', this.tabBiddingClick.bindAsEventListener(this));
    this.textBidderNote = $('textBidderNote');
    try {
      this.pageCreate();
    } catch (e) { }
  }
});


var _LBO;
window.onload=function() {
  _LBO = new LBO();
};


