$(document).ready(function(){
    fetchTimestamp = function(){
        return parseInt($('#timestamp').text());
    };

    // Default frequency for auction updating and time sync
    var auctionUpdateTime = 10;

    if($('#auctionupdatefrequency')){
        auctionUpdateTime = parseInt($('#auctionupdatefrequency').text());
    }

    // Convert it to milisecond
    auctionUpdateTime = auctionUpdateTime * 1000;

    // Variable to hold auction data
    var auctions = '';

    // Collecting auction data, the layer id and auction id
    $('.auction-item').each(function(){
        var auctionId    = $(this).attr('id');
        var auctionTitle = $(this).attr('title');
        var counter      = $('#' + auctionId + ' .countdown');

        if(counter){
            if(counter.attr('title') > fetchTimestamp()){
                auctions = auctions + auctionId + '=' + auctionTitle + '&';
            }
        }
    });

    var nocacheTimestamp = new Date();
    // Main countdown for updating auction and flashing
    setInterval(function(){
        if(auctions){
            if($('#bidHistoryTable').length){
                getStatusUrl = '/getstatus.php?histories=yes&time='+nocacheTimestamp.getTime();
            }else{
                getStatusUrl = '/getstatus.php?time='+nocacheTimestamp.getTime();
            }

            $.ajax({
                url: getStatusUrl,
                dataType: 'json',
                type: 'POST',
                timeout: 2999,
                global: false,
                data: auctions,
                success: function(data){
					$('#time').text(data.serverTime);
                    $.each(data, function(i, item){
						if(item == data.serverTime){ return true; }
                        var auctionBlock        = $('#' + item.Auction.element);
                        var auctionEndTime      = $('#' + item.Auction.element + ' .countdown').attr('title');
                        var auctionLatestBidder = $('#' + item.Auction.element + ' .bid-bidder').text();
                        var auctionCountdown    = $('#' + item.Auction.element + ' .countdown');
                        var auctionClosesOn     = $('#' + item.Auction.element + ' .closes-on');

                        if(auctionLatestBidder != item.LastBid.username){
                            $('#' + item.Auction.element + ' .bid-bidder').html(item.LastBid.username);
                        }

                        if(auctionEndTime != item.Auction.end_time){
                            auctionCountdown.attr('title', item.Auction.end_time);

                            $('#' + item.Auction.element + ' .bid-price').html(item.Auction.start_price);

                            if(document.getElementById('bidHistoryTable')){
                                if($('#bidHistoryTable p').text()){
                                    $('#bidHistoryTable p').remove();
                                }

                                $('#bidHistoryTable tbody tr').remove();

                                $.each(item.Histories, function(n, tRow){
                                    var row = '<tr><td>' + tRow.Bid.created + '</td><td>' + tRow.User.username + '</td></tr>';

                                    $('#bidHistoryTable tbody').append(row);
                                });

                                auctionClosesOn.text(item.Auction.closes_on);

                                $('#' + item.Auction.element + ' .bid-savings-percentage').html(item.Auction.savings.percentage);
                                $('#' + item.Auction.element + ' .bid-savings-price').html(item.Auction.savings.price);
                            }
							//animate yellow and then white
                        }

                        if(item.Auction.peak_only == 1 && item.Auction.isPeakNow == 0){
                            auctionCountdown.text('Paused');

                            $('#' + item.Auction.element + ' .bid-button a').hide();
                            if($('#' + item.Auction.element + ' .bid-button p').text() == ''){
                                $('#' + item.Auction.element + ' .bid-button').append('<p>Peak Only Auction</p>');
                            }
                        }else{
                            if(item.Auction.end_time - item.Auction.serverTimestamp > 0){
                                auctionCountdown.text(item.Auction.end_time_string);

                                if(item.Auction.time_left <= 10){
                                    auctionCountdown.css('color', '#ff0000');
                                }else{
                                    auctionCountdown.removeAttr('style');
                                }
                            }

                            if($('#' + item.Auction.element + ' .bid-button p').text()){
                                $('#' + item.Auction.element + ' .bid-button a').show();
                                $('#' + item.Auction.element + ' .bid-button p').remove();
                            }
                        }

                        if(item.Auction.time_left < 1 && item.Auction.closed == 1){
                            auctionCountdown.text('Ended');
                            $('#' + item.Auction.element + ' .bid-button').hide();
                            $('#' + item.Auction.element + ' .bid-bookbidbutler').hide();

                        }
						else if(item.Auction.time_left == 3 && item.Auction.closed == 0){
                            auctionCountdown.text('Going Once!');
                        }
						else if(item.Auction.time_left == 2 && item.Auction.closed == 0){
                            auctionCountdown.text('Going Twice!');
                        }
						else if(item.Auction.time_left == 1 && item.Auction.closed == 0){
                            auctionCountdown.text('Hurry!');
                        }
                    });
                },

                error: function(XMLHttpRequest, textStatus, errorThrown){
                    //$('.countdown').text(textStatus);
                }
            });
        } else {
            $.ajax({
                url: '/gettime.php',
                dataType: 'json',
                type: 'POST',
                timeout: 2999,
                global: false,
                success: function(data){
					$('#time').text(data.serverTime);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){

				}
			});
		}
    }, auctionUpdateTime);

    // Function for bidding
    $('.bid-button-link').click(function(){
        var auctionElement = 'auction_' + $(this).attr('title');
        var bidButton      = $('#' + auctionElement + ' .bid-button');
        var bidLoading     = $('#' + auctionElement + ' .bid-loading');
        var bidMessage     = $('#' + auctionElement + ' .bid-message');

        bidButton.hide();
        bidLoading.show();

        $.ajax({
            url: $(this).attr('href'),
            dataType: 'json',
			cache: false,
            success: function(data){
                bidMessage.html(data.Auction.message).show(1).animate({opacity: 1.0}, 2000).hide(1);
                bidButton.show();
                bidLoading.hide();
            }
        });

        return false;
    });

    if($('.thumbImage').length){
        $('.thumbImage').click(function(){
            $('.largeImage').fadeOut('fast').attr('src', $(this).attr('href')).fadeIn('fast');
            return false;
        });
    }

	$('#categories').hover(
		function() {
			$('#cats').show();
		},
		function() {
			$('#cats').hide();
		}
	);

});
