﻿var masterPagePrefix = 'MasterPage_MasterPageContentPlaceHolder_';
var pageHeight;
var pageWidth;
var timeDifference;
var serverTime = new Date();
var serverUTCOffset = 0;
var lastLotUpdateTime = new Date(); //Client time
var auctionFirstLotClosesTime = new Date();
var auctionIDElement;
var webServiceInterval = "";
var refreshTime = 0;
var lotDBID = -1;
var auctionID = -1;
var lBidPrice = -1;
var uIDElement;
var uID = -1;
var isInternetConnectionErrorOpen = 0;
var connectionImage = new Image();
connectionImage.src = "/images/connection_alert.jpg";
var alertHTML = '<p style="text-align: center; font-weight: bold; color: Red; font-size: 14px;"><img src="' + connectionImage.src + '" alt=""><br/><br>Please Check Your Internet Connection</p>';
var clockHandler;
var bidConfirmatonWindowTitle;
var yOffset = 0;
var currencyConversionRate = 0;

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

var LotCatalogDebug = false;

//Create debugging window
if (LotCatalogDebug == true) var debugWindow = window.open("/javaScript/auction/debugPage.htm", "debugWindow");

function EndRequestHandler(sender, args) {
    if (args.get_error() != undefined) {
    
        /*
        var errorMessage;
        if (args.get_response().get_statusCode() == '200') {
            errorMessage = args.get_error().message;
        }
        else {
            errorMessage = 'An unspecified error occurred. ';
        }
        
        alert(errorMessage);
        */

        args.set_errorHandled(true);
        
        if (isInternetConnectionErrorOpen == 0) {
            internetConnectionWindow();
            isInternetConnectionErrorOpen = 1;
        }

    }
    else {
        
        if (isInternetConnectionErrorOpen == 1) {
            MochaUI.closeWindow(document.getElementById('internetConnection'));
            isInternetConnectionErrorOpen = 0;
        }
        
    }
}

var bidConfirmationWindow = function() {
    new MochaUI.Window({
        id: 'bidconfirmation',
        title: bidConfirmatonWindowTitle,
        minimizable: false,
        loadMethod: 'iframe',
        contentURL: '_bidConfirmation.aspx?AID=' + auctionID + '&LID=' + lotDBID + '&B=' + lBidPrice,
        type: 'modal',
        width: 490,
        height: 570,
        y: yOffset
    });
};

var internetConnectionWindow = function() {
    new MochaUI.Window({
        id: 'internetConnection',
        title: 'Internet Connection Error',
        minimizable: false,
        loadMethod: 'html',
        content: alertHTML,
        type: 'notification',
        width: 400,
        height: 150,
        bodyBgColor: [255, 255, 255]
    });
};

function closeWindow(id) {
    MochaUI.closeWindow($(id));
}

//Retrieve page dimensions
function getPageDimensions() {

    if (window.innerHeight && window.scrollMaxY) { // Firefox 
        pageWidth = window.innerWidth + window.scrollMaxX;
        pageHeight = window.innerHeight + window.scrollMaxY;
    }
    else if (document.documentElement.clientHeight) {
        pageWidth = document.documentElement.clientWidth;
        pageHeight = document.documentElement.clientHeight;
    }
    else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
    {
        pageWidth = document.body.offsetWidth + document.body.offsetLeft;
        pageHeight = document.body.offsetHeight + document.body.offsetTop;
    }

}

function handleOnMouseOver(row) {
    row.oldBackgroundColor = row.style.backgroundColor;
    row.style.backgroundColor = '#f4f6d1';
}

function handleOnMouseOut(row) {
    row.style.backgroundColor = row.oldBackgroundColor;
}

function handleRedirect(url) {
    window.location.href = url;
    return;
}

function writeDebug(text) {

    if (LotCatalogDebug == false) return;
    if (debugWindow) {
        debugWindow.document.getElementById("debugOutput").innerHTML += text + "<br>";
    }
    
}

function init(_uid, _auctionID, _refreshTime) {

    //Debug
    writeDebug("Init");
    
    uIDElement = document.getElementById(masterPagePrefix + "uHiddenField");
    uIDElement.value = _uid;

    refreshTime = _refreshTime;
    
    //Set reference to hidden field
    auctionIDElement = document.getElementById(masterPagePrefix + "auctionIDHiddenField");
    auctionIDElement.value = _auctionID;

    //Set first lot closes time
    auctionFirstLotClosesTime = document.getElementById(masterPagePrefix + "auctionFirstLotClosesHiddenField").value;
        
    //Get page dimensions
    getPageDimensions();

    if (_refreshTime != null) {
     
        //Create lot container
        setWrapper('lotContainerWrapper');
        var lotContainer = createLotContainer(1, pageWidth - 20, 100, 0, 0);
        lotContainer.setBorderSize(1);

        //Debug
        writeDebug("Created lot container");

        //Set client clock
        AuctionFeedWebService.GetClock(getClockCallBackHandler, getLotInfoCallBackErrorHandler);

        //Debug
        writeDebug("Set Get Clock handler");

    }
}


function initWithoutAJAX(_uid, _auctionID) {

    //Debug
    writeDebug("Init");

    uIDElement = document.getElementById(masterPagePrefix + "uHiddenField");
    uIDElement.value = _uid;


    //Set reference to hidden field
    auctionIDElement = document.getElementById(masterPagePrefix + "auctionIDHiddenField");
    auctionIDElement.value = _auctionID;

    //Set first lot closes time
    auctionFirstLotClosesTime = document.getElementById(masterPagePrefix + "auctionFirstLotClosesHiddenField").value;

    //Get page dimensions
    getPageDimensions();

    //Set client clock
    AuctionFeedWebService.GetClock(getClockCallBackHandler, getLotInfoCallBackErrorHandler);

    //Debug
    writeDebug("Set Get Clock handler");

}

function startWebServiceCall() {
    //showLoader();
    AuctionFeedWebService.GetAuctionLotsForAjax(auctionIDElement.value, uIDElement.value, getLotInfoCallBackHandler, getLotInfoCallBackErrorHandler);
    //var t = setTimeout("startWebServiceCall()", 2000);

    //Debug
    writeDebug("Started Web Service Call");
}

function getClockCallBackHandler(a, b) {
       
    //Debug
    writeDebug("Clock CallBackHandler invoked");

    var returnPairs = a.split(",",2);
    var returnedServerUTCTime = returnPairs[0];
    var returnedServerUTCOffset = returnPairs[1];
    serverUTCOffset = returnedServerUTCOffset;
    
    var currentTime = new Date();
    var serverTime = new Date();
    var currentUTCTime = new Date();

    currentUTCTime.setTime(currentTime.getTime() + (currentTime.getTimezoneOffset() * 60000));
    serverTime.setTime(returnedServerUTCTime);

    timeDifference = currentTime.getTime() - serverTime.getTime();

    if (timeDifference > 0 || timeDifference < 0) {
    
    updateClock();

    //Debug
    writeDebug("updateClock() routine being called from Clock CallBackHandler");

    }

}

function getLotInfoCallBackErrorHandler(a, b) {

    //alert("Please check your internet connection.");
    
    //Debug
    writeDebug("getLotInfoCallBackErrorHandler invoked");

}

function getLotInfoCallBackHandler(a, b) {

    //Check for currency conversion rate
    if (document.getElementById(masterPagePrefix + "currencyRateHiddenField")) currencyConversionRate = document.getElementById(masterPagePrefix +"currencyRateHiddenField").value;

    //Debug
    writeDebug("getLotInfoCallBackHandler invoked");

    //hideLoader();

    var retrievedLotList = [];
    var newLotList = [];
    var updatedLotList = [];
    var removedLotList = [];

    //Set last update time
    lastLotUpdateTime = new Date();
    
    for (var i = 0; i < a.length; i++) {

        retrievedLotList[retrievedLotList.length] = a[i].Lot_ID;
        
        //Check for new lots
        if (!Lot_Instances_Index[a[i].Lot_ID]) {
            newLotList[newLotList.length] = i; 
        }
        else {
            updatedLotList[updatedLotList.length] = i; 
        }

        //Check for removed lots

    }

    //Debug
    writeDebug("getLotInfoCallBackHandler: Received " + a.length + " lots");

    //Remove lots
    for (var i = 1; i < lotIndex; i++) {
    if (Lot_Instances[i] != null) {
    if (indexInArray(retrievedLotList, Lot_Instances[i].getLotDBID()) == -1) {

                //Debug
    writeDebug("getLotInfoCallBackHandler: Removed Lot " + i + " Lot ID: " + Lot_Instances[i].getLotDBID());

                removeLot(i, Lot_Instances[i].getLotDBID());

            }
    }
    }

    //Debug
    writeDebug("getLotInfoCallBackHandler: Calling reposition lots");

    //Reposition lots
    repositionLots(1);

    //Add new lots
    for (var i = 0; i < newLotList.length; i++) {

        //Debug
    writeDebug("getLotInfoCallBackHandler: Adding Lot " + i + " Lot ID: " + a[newLotList[i]].Lot_ID);

    var ID = a[newLotList[i]].Lot_ID;
    var title = "Lot # " + a[newLotList[i]].LotNumberLetterCombined + ' - ' + a[newLotList[i]].Description;
    var startDate = a[newLotList[i]].LotBidStartDateTime;
    var endDate = a[newLotList[i]].LotBidEndDateTime;
    var bidPrice = formatCurrency(a[newLotList[i]].BidPrice * currencyConversionRate);
    var originalBidPrice = a[newLotList[i]].BidPrice;
    var reservePrice = a[newLotList[i]].ReservePrice * currencyConversionRate;
    var numberOfBids = a[newLotList[i]].NumberOfBids;
    var originalNextBidPrice = a[newLotList[i]].NextBidPrice;
    var nextBidPrice = formatCurrency(a[newLotList[i]].NextBidPrice * currencyConversionRate);
    var lotPhoto = a[newLotList[i]].LotPhoto;
    var auctionID = a[newLotList[i]].Auction_ID;
    var bidUserID = a[newLotList[i]].BidUser_ID;
    var description = a[newLotList[i]].Description;
    var lotNumber = a[newLotList[i]].LotNumberLetterCombined;
    var originalLotEndDate = a[newLotList[i]].OriginalLotBidEndDateTime;
    var isExtended = a[newLotList[i]].IsExtended;
    var userMaxBid = a[newLotList[i]].UserMaxBid;

    //Check for currency code
    var currencyType = "";
    if (document.getElementById(masterPagePrefix + "currencyCodeHiddenField")) currencyType = document.getElementById(masterPagePrefix + "currencyCodeHiddenField").value;

        //Add new lot
    addLot(ID, title, bidPrice, numberOfBids);

        //Debug
    writeDebug("getLotInfoCallBackHandler: Added Lot " + i + " Lot ID: " + a[newLotList[i]].Lot_ID);

        var lot = Lot_Instances[Lot_Instances_Index[ID]];

        //Set Lot Description
    lot.setDescription(description);

        //Set Lot Number
    lot.setLotNumber(lotNumber);
        
    //Set Auction_ID
    lot.setAuctionID(auctionID);
        
    //Set update date/time for lot
    lot.setLastUpdateTime(new Date())

        //Set bidding USER_ID
    lot.setBidUserID(bidUserID);
       
    if (bidUserID == lot.getBidUserID() && bidUserID == uIDElement.value && lot.getBidUserID() != 0 && bidUserID != 0) {
    lot.setHighBidderMessage("HighBidder");
    }
    else {
    lot.setHighBidderMessage("");
    }

        //Set start & end dates
    lot.setLotStartDate(startDate);
    lot.setLotEndDate(endDate);

        //Get Time Remaining
    var dateDiffArray = [];
    dateDiffArray = dateDiff(lot.getLotEndDate(), serverTime);
        
    var timeRemainingString = dateDiffArray[1] + "h " + dateDiffArray[2] + "m " + dateDiffArray[3] + "s";
    lot.setTimeRemaining(timeRemainingString);
        
    //Debug
    writeDebug("getLotInfoCallBackHandler: Set Lot " + i + " Lot ID: " + a[newLotList[i]].Lot_ID + " time remaining");

        //Set currency type
    lot.setCurrencyType(currencyType);
        
    //Set bid button
    lot.setBidButton(nextBidPrice);

        //Set icon
    lot.setIcon(lotPhoto);

        //Set next bid price
    lot.setOriginalNextBidPrice(originalNextBidPrice);
    lot.setNextBidPrice(a[newLotList[i]].NextBidPrice * currencyConversionRate);

        //Set bid price -- Set bid price before reserve price!
    lot.setBidPrice(originalBidPrice);

        //Set reserve price
    lot.setReservePrice(reservePrice);

        //Set bid price
    lot.setCurrentBid(bidPrice);

    //Set extended
    lot.setExtended(isExtended);

    //Set User Max Bid
    lot.setMaxBidPrice(userMaxBid, originalBidPrice);
    
        //Enable lot button
    lot.enable();

        //Debug
    writeDebug("getLotInfoCallBackHandler: Calling reposition lots");

        //Reposition lots
    repositionLots(1);

    }

    //Update lots
    for (var i = 0; i < updatedLotList.length; i++) {

        //Debug
    writeDebug("getLotInfoCallBackHandler: Updating Lot " + i + " Lot ID: " + a[updatedLotList[i]].Lot_ID);

    var ID = a[updatedLotList[i]].Lot_ID;
    var title = "Lot # " + a[updatedLotList[i]].LotNumberLetterCombined + ' - ' + a[updatedLotList[i]].Description;
    var startDate = a[updatedLotList[i]].LotBidStartDateTime;
    var endDate = a[updatedLotList[i]].LotBidEndDateTime;
    var bidPrice = formatCurrency(a[updatedLotList[i]].BidPrice * currencyConversionRate);
    var originalBidPrice = a[updatedLotList[i]].BidPrice;
    var reservePrice = a[updatedLotList[i]].ReservePrice * currencyConversionRate;
    var numberOfBids = a[updatedLotList[i]].NumberOfBids;
    var originalNextBidPrice = a[updatedLotList[i]].NextBidPrice;
    var nextBidPrice = formatCurrency(a[updatedLotList[i]].NextBidPrice * currencyConversionRate);
    var lotPhoto = a[updatedLotList[i]].LotPhoto;
    var auctionID = a[updatedLotList[i]].Auction_ID;
    var bidUserID = a[updatedLotList[i]].BidUser_ID;
    var description = a[updatedLotList[i]].Description;
    var lotNumber = a[updatedLotList[i]].LotNumberLetterCombined;
    var originalLotEndDate = a[updatedLotList[i]].OriginalLotBidEndDateTime;
    var isExtended = a[updatedLotList[i]].IsExtended;
    var userMaxBid = a[updatedLotList[i]].UserMaxBid;

    var currencyType = "";
    if (document.getElementById(masterPagePrefix + "currencyCodeHiddenField")) currencyType = document.getElementById(masterPagePrefix + "currencyCodeHiddenField").value;

        var lot = Lot_Instances[Lot_Instances_Index[ID]];

        //Set update date/time for lot
    lot.setLastUpdateTime(new Date());

        //Set currency type
    lot.setCurrencyType(currencyType);
        
    //Perform checks
    if (title != lot.getTitle()) {
    lot.setTitle(title);
    }

        //Get Time Remaining
    //var dateDiffArray = [];
    //dateDiffArray = dateDiff(lot.getLotEndDate(), serverTime);
    //var timeRemainingString = dateDiffArray[1] + "h " + dateDiffArray[2] + "m " + dateDiffArray[3] + "s";
    //lot.setTimeRemaining(timeRemainingString);

        //Now determine what indicator to use
    //Determine if bid has changed
        
    if (lot.getBidPrice() != originalBidPrice) {

            if (bidUserID != lot.getBidUserID() && bidUserID != uIDElement.value && lot.getBidUserID() != 0) {
                
    //Have we been outbid?
    if (lot.getBidUserID() == uIDElement.value) {

                    //If the lot has already been marked as "outbid" (because of Max Bid system), do not set
    if (lot.getHighBidderMessage() != "You've been outbid") {
    fullFadeBg('lotTable' + lot.getID(), '#FFFFFF', '#ffa2a2', '4000');
    lot.setHighBidderMessage("Outbid");
    }

                }
    else {
    fullFadeBg('lotTable' + lot.getID(), '#FFFFFF', '#FFFEA2', '4000');
    lot.setHighBidderMessage("");
    }
               
    }
    else if ((bidUserID != lot.getBidUserID() && bidUserID == uIDElement.value) ||
    (bidUserID == lot.getBidUserID() && bidUserID == uIDElement.value)) {
    //We've just won the bid
    fullFadeBg('lotTable' + lot.getID(), '#FFFFFF', '#a2ffa9', '4000');
    lot.setHighBidderMessage("HighBidder");
    }
    else {
    //If the lot has already been marked as "outbid" (because of Max Bid system), do not set
    if (lot.getHighBidderMessage() != "You've been outbid") {
    fullFadeBg('lotTable' + lot.getID(), '#FFFFFF', '#FFFEA2', '4000');
    lot.setHighBidderMessage("");
    }
    }
            
    }

        //Set Auction_ID
    lot.setAuctionID(auctionID);

        //Set bidding USER_ID
    lot.setBidUserID(bidUserID);

        //Set description
    lot.setDescription(description);

        //Set lot number
    lot.setLotNumber(lotNumber);
        
    //Set number of bids
    lot.setNumberOfBids(numberOfBids);

        //Set next bid price
    lot.setOriginalNextBidPrice(originalNextBidPrice);
    lot.setNextBidPrice(originalNextBidPrice * currencyConversionRate);
        
    //Set bid price -- Set bid price before reserve price!
    lot.setBidPrice(originalBidPrice);

        //Set reserve price
    lot.setReservePrice(reservePrice);

        //Set start & end dates
    lot.setLotStartDate(startDate);
    lot.setLotEndDate(endDate);
        
    //Set bid button
    lot.setBidButton(nextBidPrice);

        //Set bid price
    lot.setCurrentBid(bidPrice);

    //Set extended
    lot.setExtended(isExtended);
    
    //Set User Max Bid
    lot.setMaxBidPrice(userMaxBid, originalBidPrice );
    
        //Enable lot button
    lot.enable();

        //Debug
    writeDebug("getLotInfoCallBackHandler: Calling reposition lots");

        //Reposition lots
    repositionLots(1);
    }

   
    //Clear
    newLotList.length = 0;
    updatedLotList.length = 0;
    retrievedLotList.length = 0;

}

function indexInArray(arr, val) {
    for (var i = 0; i < arr.length; i++) if (arr[i] == val) return i;
    return -1;
    } 

function updateClock() {

    //Debug
    //writeDebug("updateClock() invoked");

    var currentTime = new Date();

    currentTime.setTime(currentTime.getTime() - timeDifference);
    serverTime = currentTime;
        
    var displayHours = currentTime.getHours();
    var displayMinutes = currentTime.getMinutes();
    var displaySeconds = currentTime.getSeconds();

    // Pad the minutes and seconds with leading zeros, if required
    displayMinutes = (displayMinutes < 10 ? "0" : "") + displayMinutes;
    displaySeconds = (displaySeconds < 10 ? "0" : "") + displaySeconds;

    // Choose either "AM" or "PM" as appropriate
    var timeOfDay = (displayHours < 12) ? "AM" : "PM";

    // Convert the hours component to 12-hour format if needed
    displayHours = (displayHours > 12) ? displayHours - 12 : displayHours;

    // Convert an hours component of "0" to "12"
    displayHours = (displayHours == 0) ? 12 : displayHours;

    // Compose the string for display
    var displayTimeString = displayHours + ":" + displayMinutes + ":" + displaySeconds + " " + timeOfDay;

    //Update the time display
    //document.getElementById("clock").innerHTML = "Server time: " + displayTimeString;
   
    //Update first lot closes time
    var flcDate = new Date(auctionFirstLotClosesTime);
    var td = ((currentTime.getTimezoneOffset() / 60) - serverUTCOffset);
    var adjustedCurrentTime = dateAdd('h', td, serverTime);
    
    if (currentTime.getTime() - flcDate.getTime() < 0) {
    var dateDiffArray = [];
    dateDiffArray = dateDiff(flcDate, adjustedCurrentTime);
    
    var timeRemainingString = dateDiffArray[0] + " days, " + dateDiffArray[1] + " hrs, " + dateDiffArray[2] + " min, " + dateDiffArray[3] + " sec";
    document.getElementById("auctionClosesTimer").innerHTML = "in " + timeRemainingString;
    }
    
    //Debug
    writeDebug("updateClock(): Lot count = " + lotCount);

    // Iterate among lots to update Time Remaining smoothly
    for (var i = 0; i < Lot_Instances.length; i++) {

        var lot = Lot_Instances[i];
    if (lot != null) {
    var dateDiffArray = [];
    dateDiffArray = dateDiff(lot.getLotEndDate(), serverTime);
    if (lot.getLotEndDate().getTime() - serverTime.getTime() >= 0) {
    var timeRemainingString = dateDiffArray[1] + "h " + dateDiffArray[2] + "m " + dateDiffArray[3] + "s";
    lot.setTimeRemaining(timeRemainingString);
                
    //Debug
    writeDebug("updateClock(): Set time remaining for lot " + i);

            }
    }
        
    }

    clearTimeout(clockHandler);
    clockHandler = setTimeout('updateClock()', 1000);

}

function dateDiff(firstDate, secondDate) {

    diff = new Date();

    diff.setTime(Math.abs(firstDate.getTime() - secondDate.getTime()));

    timediff = diff.getTime();

    //weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
    //timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

    days = Math.floor(timediff / (1000 * 60 * 60 * 24));
    timediff -= days * (1000 * 60 * 60 * 24);

    hours = Math.floor(timediff / (1000 * 60 * 60));
    timediff -= hours * (1000 * 60 * 60);

    mins = Math.floor(timediff / (1000 * 60));
    timediff -= mins * (1000 * 60);

    secs = Math.floor(timediff / 1000);
    timediff -= secs * 1000;

    var diffArray = [];
    diffArray[0] = days;
    diffArray[1] = hours;
    diffArray[2] = mins;
    diffArray[3] = secs;

    return diffArray; 
    }

function formatCurrency(num) {
    /* Original:  Cyanide_7 (leo7278@hotmail.com) */
    /* Web Site:  http://www7.ewebcity.com/cyanide7 */
    
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num);
}

function confirmBid(_lotDBID, _bidPrice) {
    lotDBID = _lotDBID;
    auctionID = auctionIDElement.value;
    lBidPrice = _bidPrice;

    var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
    var dsocleft = document.all ? iebody.scrollLeft : pageXOffset
    var dsoctop = document.all ? iebody.scrollTop : pageYOffset
    yOffset = dsoctop + 5;

    //Set bid confirmation window title
    try {
        var lot = Lot_Instances[Lot_Instances_Index[_lotDBID]];
        bidConfirmatonWindowTitle = "Lot# " + lot.getLotNumber() + " - " + lot.getDescription();
    }
    catch (e) {

    }
    
    bidConfirmationWindow();
}

function buyItNow(_lotDBID) {

    if (uIDElement.value == null || uIDElement.value < 1) {
        alert("You must be logged in to place a bid.");
    }
    else {
        var lot = Lot_Instances[Lot_Instances_Index[_lotDBID]];
        var nextBidPrice = lot.getNextBidPrice();

        //Disable lot
        lot.disable();

        //Stop web service
        clearInterval(webServiceInterval);

        //Call web service
        AuctionFeedWebService.BuyItNow(uIDElement.value, auctionIDElement.value, lotDBID, buyItNowHander);

    }
    
}

function placeBid(_lotDBID) {

    if (uIDElement.value == null || uIDElement.value < 1) {
       alert("You must be logged in to place a bid.");
    }
    else {

            var lot = Lot_Instances[Lot_Instances_Index[_lotDBID]];
            var nextBidPrice = lot.getOriginalNextBidPrice();

            //Disable lot
            lot.disable();

            //Stop web service
            clearInterval(webServiceInterval);

            //Call web service
            AuctionFeedWebService.PlaceBid(uIDElement.value, auctionIDElement.value, lotDBID, "USD", 1.00, nextBidPrice, placeBidHander, placeBidErrorHandler, _lotDBID);

        //Update clock in case of delay
        clearTimeout(clockHandler);
        updateClock();
        
    }
    
}

function placeBidHander(a, b) {

    if(a == "Failure")  {
        alert("You've entered an invalid bid amount.  Please re-enter your bid.");
    }
    
    if(a == "SuccessButOutbidByMaxbid" || a == "MaxBidFail") {

        //Set lot to outbid
        var lot = Lot_Instances[Lot_Instances_Index[b]];

        lot.setHighBidderMessage("Outbid");

        alert("You've been outbid.  Another user already has a high max bid in the system.");

        fullFadeBg('lotTable' + lot.getID(), '#FFFFFF', '#ffa2a2', '4000');

    }
   
    //Call immediately and then resume periodic inteval
    startWebServiceCall();
    clearInterval(webServiceInterval);
    webServiceInterval = setInterval('startWebServiceCall()', refreshTime);

}

function placeBidErrorHandler(a, b) {

    alert("Your bid did not register in the system.  Please re-enter your bid.");
    
}

function buyItNowHander(a, b) {

    //Call immediately and then resume periodic inteval
    startWebServiceCall();
    clearInterval(webServiceInterval);
    webServiceInterval = setInterval('startWebServiceCall()', refreshTime);

}

function showLoader() {
    document.getElementById('loader').style.visibility = 'visible';
    document.getElementById('loader').style.display = '';
}

function hideLoader() {
    document.getElementById('loader').style.visibility = 'hidden';
    document.getElementById('loader').style.display = 'none';
}

function dateAdd(p_Interval, p_Number, p_Date) {
//    if (!isDate(p_Date)) { return "invalid date: '" + p_Date + "'"; }
    if (isNaN(p_Number)) { return "invalid number: '" + p_Number + "'"; }

    p_Number = new Number(p_Number);
    var dt = new Date(p_Date);
    
    switch (p_Interval.toLowerCase()) {
        case "yyyy": 
            {// year
                dt.setFullYear(dt.getFullYear() + p_Number);
                break;
            }
        case "q": 
            { // quarter
                dt.setMonth(dt.getMonth() + (p_Number * 3));
                break;
            }
        case "m": 
            { // month
                dt.setMonth(dt.getMonth() + p_Number);
                break;
            }
        case "y": // day of year
        case "d": // day
        case "w": 
            { // weekday
                dt.setDate(dt.getDate() + p_Number);
                break;
            }
        case "ww": 
            { // week of year
                dt.setDate(dt.getDate() + (p_Number * 7));
                break;
            }
        case "h": 
            { // hour
                dt.setHours(dt.getHours() + p_Number);
                break;
            }
        case "n": 
            { // minute
                dt.setMinutes(dt.getMinutes() + p_Number);
                break;
            }
        case "s": 
            { // second
                dt.setSeconds(dt.getSeconds() + p_Number);
                break;
            }
        case "ms": 
            { // second
                dt.setMilliseconds(dt.getMilliseconds() + p_Number);
                break;
            }
        default: 
            {
                return "invalid interval: '" + p_Interval + "'";
            }
    }
    return dt;
}