$(document).ready(function(){
    fetchTimestamp = function(){
        return parseInt($('#timestamp').text());
    };

    // Default frequency for auction updating and time sync
    var auctionUpdateTime = 1;

    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){

                    $.each(data, function(i, item){
                        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 || (item.Auction.exclusive == 1 && auctionLatestBidder != item.LastBid.username && auctionLatestBidder != '')){
                            auctionCountdown.attr('title', item.Auction.end_time);

                            $('#' + item.Auction.element + ' .bid-price').html(item.Auction.start_price);
							$('#' + item.Auction.element + ' .bid-price2').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><td>' + tRow.Bid.description + '</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);
								
                            }

                            $('#' + item.Auction.element + ' .countdown, #' + item.Auction.element + ' .bid-price, #' + item.Auction.element + ' .bid-price2, #' + item.Auction.element + ' .bid-bidder, #' + item.Auction.element + ' .bid-savings-price, #' + item.Auction.element + ' .bid-savings-percentage, #' + item.Auction.element + ' .closes-on').animate( { backgroundColor: 'red' }, 500).animate( { backgroundColor: 'white' }, 1000);
                        }

                        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 style="margin:0;padding:0;font-size:11px;color:#0A2EF3;"><strong>Will Resume at 10:00am EST</strong></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 == 1 && item.Auction.closed == 0){
                            auctionCountdown.text('00:00:01');
                        }
						else if(item.Auction.time_left < 1 && item.Auction.closed == 0  && item.Auction.isPeakNow == 1){
                            auctionCountdown.text('GOING');
                        }
                    });
                },

                error: function(XMLHttpRequest, textStatus, errorThrown){
                    //$('.countdown').text(textStatus);
                }
            });
        }
    }, 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');
		var userBids     = $('#' + auctionElement + ' .your-bids');
		var remainingBids     = $('#' + auctionElement + ' .remaining-bids');

        bidButton.hide(1);
        bidLoading.show(1);
		

        $.ajax({
            url: $(this).attr('href'),
            dataType: 'json',
            success: function(data){
                bidMessage.html(data.Auction.message).show(1).animate({opacity: 1.0}, 2000).hide(1);
				 $('.remaining-bids').animate( { backgroundColor: 'red' }, 500).animate( { backgroundColor: '#DFDFDF' }, 1000);
				$('#' + 'snag_it_now' + ' .your-bids').html(data.Auction.userbids);
				$('#' + 'snag_it_now' + ' .snag-it-savings').html(data.Auction.snag_now_price);
				$('.remaining-bids').html(data.Auction.remainingBids);
                bidButton.show(1);
                bidLoading.hide(1);
            }
        });
		
		

        return false;
    });

    if($('.productImageThumb').length){
        $('.productImageThumb').click(function(){
            $('.productImageMax').fadeOut('fast').attr('src', $(this).attr('href')).fadeIn('fast');
            return false;
        });
    }

    if($('#CategoryId').length){
        $('#CategoryId').change(function(){
            document.location = '/categories/view/' + $('#CategoryId option:selected').attr('value');
        });
    }

    if($('#myselectbox').length){
        $('#myselectbox').change(function(){
            document.location = '/categories/view/' + $('#myselectbox option:selected').attr('value');
        });
    }

	$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

	$("ul.topnav li span").click(function() { //When trigger is clicked...

		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() {
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

});
