LUCKYCHIC.auction = function() {
    var _auction_nodes = {};
    var _auction_querystring = "";
    var _getstatus_url;

    var _bidOfficialTime = $('.bid-official-time');
    var _bidBalance = $('.bid-balance');

    var _priceFixed = "";
    var _urls = {status: "/getstatus.php?",
                 time: "/gettime.php?"};

    var _timers = {status: null,
                   time: null};

    var _reqs = 0;
    var _pollErrs = 0;

    return {

        init: function() {
            var collect = function() {
                _auction_nodes[this.id] = this;
                var id_for_querystring = this.id.replace("auction_with_history_", "");
                id_for_querystring = id_for_querystring.replace("auction_", "");
                _auction_querystring += this.id + "=" + id_for_querystring + "&";
            };

            $("DIV.pollable").each(collect);

            if (_auction_querystring != "") {
                _timers.status = setInterval(LUCKYCHIC.auction.poll, 1000);
            } else if (_bidOfficialTime.length > 0) {
                _timers.time = setInterval(LUCKYCHIC.auction.getTime, 1000);
            }

            $("A.bid-trigger").click(LUCKYCHIC.auction.bid);
            $("A.seat-trigger").click(LUCKYCHIC.auction.seat);


        },

        toNumber: function(input) {
            if (typeof input === "string") {
                input = input.replace(/&#[0-9]{1,};/gi, "");
                input = input.replace(/&[a-z]{1,};/gi, "");
                input = input.replace(/[a-zA-Z]+/gi, "");
                input = input.replace(/[^0-9\,\.]/gi, "");
            }
            return input;
        },

        getTime: function() {
            var onSuccess = function(data) {
                _bidOfficialTime.text(data);
            };

            $.ajax({url: _urls.time + new Date().getTime(),
                    success: onSuccess});
        },

        poll: function() {
            _reqs++;
            $.ajax({url: _urls.status + "ms=" + new Date().getTime() + "&rn=" + _reqs + "&pe=" + _pollErrs,
                    dataType: "json",
                    type: "POST",
                    data: _auction_querystring,
                    success: LUCKYCHIC.auction.updatePage,
                    error: LUCKYCHIC.auction.handleError,
                    timeout: 950
                   });
        },

        handleError: function(xhr, textStatus, errorThrown) {
            _pollErrs++;
        },

        updatePage: function(data) {
            //clearInterval(_timers.status);

            var responseIterator = function(i, item) {

                if (i == 0) {
                    if (item.Auction) _bidOfficialTime.text(item.Auction.serverTimeString);
                    if (item.Balance) _bidBalance.text(item.Balance.balance);
                }


                var node = $(_auction_nodes[item.Auction.element]);

                var price_on_page = node.find("SPAN.bid-price-fixed:first").text() || node.find("SPAN.bid-price:first").text();

                price_on_page = LUCKYCHIC.auction.toNumber(price_on_page);

                node.find(".bid-bidder").text(item.LastBid.username);

                if (item.Message && item.Message.message != "") {
                    node.find(".bid-message").text(item.Message.message);
                }


                if (price_on_page != LUCKYCHIC.auction.toNumber(item.Auction.price)) {
                    node.find("SPAN.bid-price").text(item.Auction.price);
                    node.find("SPAN.bid-price-fixed").text(item.Auction.price);


                    if (item.Histories) {
                        node.find(".history TABLE TBODY TR").remove();
                        var history_rows = "";
                        var previous_date = "";
                        var history_iterator = function(n, row) {
                            date_parts = row.Bid.created.split(" at ");
                            if (date_parts[0] != previous_date) {
                                history_rows += '<tr><td colspan="3">' + date_parts[0] + '</td></tr>';
                                previous_date = date_parts[0];
                            }
                            var row_class = (n % 2 == 0)? "":"alt";
                            history_rows += '<tr class="' + row_class + '"><td class="date">' + date_parts[1] + '</td><td class="user">';
                            if (row.Bid.description == 'concierge bid') {
                                history_rows += row.User.username + "'s concierge";
                            } else {
                                history_rows += row.User.username;
                            }
                            history_rows += '</td><td class="price">' + row.Bid.amount + '</td></tr>';
                        };
                        $.each(item.Histories, history_iterator);
                        node.find("#bid-history DIV.scrollable-inner")[0].innerHTML = '<table cellspacing="0">' + history_rows + '</table>';
                        history_rows = null;
                        item.Histories = null;
                        history_iterator = null;
                        node.find(".closes-on").text(item.Auction.closes_on);
                        node.find(".bid-savings-percentage").text(item.Auction.savings.percentage);
                        node.find(".bid-savings-price").text(item.Auction.savings.price);
                    }

                    node.find(".flashy").effect("highlight", {color: "#ffff00"}, 1500);
                }


                if ((item.Auction.peak_only == 1 && item.Auction.isPeakNow == 0)) {
                    node.find(".auction-countdown").text("Paused");
					if (item.Auction.seat == 0) {
						node.find(".bid-button-a").hide();
					}
                    if (node.find(".bid-button-p").text() == '') {
                        node.find(".bid-button").append("<p>Peak Only Auction</p>");
                    }
                } else {
                    if (item.Auction.end_time - item.Auction.serverTimestamp >= 0) {
                        node.find(".auction-countdown").text(item.Auction.end_time_string);
                        if (item.Auction.time_left <= 10) {
                            node.find(".auction-countdown").addClass('ending-soon');
                        } else {
                            node.find(".auction-countdown").removeClass('ending-soon');
                        }
                    }

                    node.find("bid-button-a").show();
                    node.find("bid-button-p").remove();
                }

                var img = node.find(".bid-button IMG:first");
                if (img.length > 0) {
                    var img_src = img.attr("src");
                } else {
                    img_src = "";
                }

                if (item.Auction.closed == 1) {
                    // the auction is over - did the user win?
                    var winner = false;
                    if (item.LastBid && item.LastBid.username) {
                        winner = node.find(".bid-bidder").hasClass(item.LastBid.username);
                    }

                    if (winner === true) {
                        node.find(".auction-countdown").text('You won!').removeClass('ending-soon');
                        node.find(".bid-message").html('<a href="/auctions/won">Purchase this item now!</a>').addClass("purchase").show();
                    } else {
                        node.find(".auction-countdown").removeClass('ending-soon').text("00:00:00");
                        node.find(".bid-message").removeClass("purchase").text("");
                        node.find("SPAN.bid-price").text(item.Auction.price);
                        node.find("SPAN.bid-price-fixed").text(item.Auction.price);
                    }

                    if (img_src.indexOf('-sold') == -1) {
                        img.attr("src", img.attr("src").replace("-over", "").replace("-bid", "-sold"));
                        img.addClass("block-rollover");
                        node.find(".bid-message").removeClass("purchase").text("");
                    }
                } else {
                    // the auction is not over
                    if (img_src.indexOf("-sold") > -1) {
                        img.attr("src", img.attr("src").replace("-over", "").replace("-sold", "-bid"));
                        img.removeClass("block-rollover");
                        node.find(".bid-message").removeClass("purchase").text("");
                    }
                }
            };

            $.each(data, responseIterator);

            data = null;
            node = null;
            price_on_page = null;
            responseIterator = null;
        },

        // Function for bidding
        bid: function(e) {
            var auction_node = $(this).closest("DIV.pollable");
            var bid_button = auction_node.find("DIV.bid-button");

            var onSuccess = function(data) {
                if (data.Auction.message != "") {
                    var message_container = auction_node.find(".bid-message");
                    var bid_balance_node = jQuery("#bid-balance");
                    if (data.Bid) {
                        var bid_debit = parseInt(data.Bid.debit);
                        if (bid_debit > 0) {
                            var bid_balance = parseInt(bid_balance_node.text().replace(/[^0-9]/, "")) - bid_debit;
                            if (bid_balance > 4) {
                                data.Auction.message += ". <strong>" + bid_balance + "</strong> chips left.";
                            } else {
                                data.Auction.message += ". <strong>" + bid_balance + "</strong> chips left.<br/>You are low on chips - <a href='/chips'>buy more</a>.";
                            }

                        }
                    }
                    bid_balance_node.text(bid_balance);

                    message_container.show();
                    message_container[0].innerHTML = data.Auction.message;
                    setTimeout(function() { if (!message_container.hasClass("purchase")) message_container.fadeOut("slow"); }, 15000);
                }
            };


            $.ajax({url: $(this).attr('href') + '&ms=' + new Date().getTime(),
                    dataType: 'json',
                    success: onSuccess});
            return false;
        },

        seat: function(e) {
            var onSuccess = function(data) {
                location.reload(true);
            };

            $.ajax({url: $(this).attr('href') + '&name=' + new Date().getTime(),
                    dataType: 'json',
                    success: onSuccess});
            return false;
        }
    };
}();

$(document).ready(LUCKYCHIC.auction.init);

