// set the bids in the top bar via ajax call
function updateShownUserBids() 
{
	
	var topBarBidsUrl = '/users/topbar_stats'; 
	
	//if AuctionSingleView exists
		//send auction id
	if ($('#AuctionSingleView').length > 0)
	{
		var auctionID =  $('.auction-item').attr('title');
		
		if (!isNaN(auctionID))
		{
			topBarBidsUrl += '?aid=' + auctionID;	
		}
	}
	
	
	//call endpoint
	$.ajax({ 
		cache: false,
		url: topBarBidsUrl,
		dataType: 'json',
		timeout: 2999,
		success: function(data)
		{
			//set bids in user bar
			var curBids = $('#bidsInTopBar').text();
			curBids = parseInt(curBids);
			
			if (curBids != data.bids)
			{
				$('#bidsInTopBar').stop(true,true);
				$('#bidsInTopBar').text(data.bids);
				$('#bidsInTopBar').css('color','red').animate( { color: '#600' }, 750 );
			}
			
			if (data.bidsOnAuction != null)
			{
				var curUsedBids = $('.auctionSingleBidsUsed').text();
				
				if (curUsedBids != data.bidsOnAuction)
				{
					$('.auctionSingleBidsUsed').stop(true,true);
					$('.auctionSingleBidsUsed').text(data.bidsOnAuction)
					$('.auctionSingleBidsUsed').css('color', 'red').animate( { color: 'black' }, 750);
			
			
			
					var bidCost = data.bidsOnAuction * $('#userBidCost').text();
					$('#userCurrentBidSpend').stop(true,true);
					$('#userCurrentBidSpend').text(Math.round(bidCost * 100)/100); 
					$('#userCurrentBidSpend').css('color', 'red').animate( { color: 'black' }, 750 );
					
					
					var buyItNowTotal = parseFloat($('#auctionRetailPrice').text()) + parseFloat($('#auctionBuyItNowShipping').text()) - parseFloat(bidCost);
					
					buyItNowTotal = Math.max(0.01, buyItNowTotal);
					
					$('.auctionBuyItNowTotal').stop(true, true);
					$('.auctionBuyItNowTotal').text(Math.round(buyItNowTotal * 100)/100);
					$('.auctionBuyItNowTotal').css('color', 'red').animate( { color: 'black' }, 750 );
					
				}
			}
		}
		
		
 
	});
	
}




$(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){

                    $.each(data, function(i, item){
                        var auctionBlock        = $('#' + item.A.e);
                        var auctionEndTime      = $('#' + item.A.e + ' .countdown').attr('title');
                        var auctionLatestBidder = $('#' + item.A.e + ' .bid-bidder').text();
                        var auctionCountdown    = $('#' + item.A.e + ' .countdown');
                        var auctionClosesOn     = $('#' + item.A.e + ' .closes-on');

                        if(auctionLatestBidder != item.L.u){
                            $('#' + item.A.e + ' .bid-bidder').html(item.L.u);
							//$('#' + item.A.e + ' .bid-bidder2').html(item.L.t);
                        }

                        if(auctionEndTime != item.A.n){
                            auctionCountdown.attr('title', item.A.n);
							
							if (item.A.s != '$0.00')
							{
                            	$('#' + item.A.e + ' .bid-price').html(item.A.s);
							}
							
                            if(document.getElementById('bidHistoryTable')){
                                if($('#bidHistoryTable p').text()){
                                    $('#bidHistoryTable p').remove();
                                }

                                $('#bidHistoryTable tbody tr').remove();

                                $.each(item.H, function(n, tRow){
                                    var row = '<tr><td>' + tRow.B.c + '</td><td>' + tRow.U.u + '</td><td>' + tRow.B.d + '</td></tr>';

                                    $('#bidHistoryTable tbody').append(row);
                                });

                                auctionClosesOn.text(item.A.c);

                                $('#' + item.A.e + ' .bid-savings-percentage').html(item.A.v.a);
                                $('#' + item.A.e + ' .bid-savings-price').html(item.A.v.p);
                            }
 							
							var toAnimate = $('#' + item.A.e + ' .countdown, #' + item.A.e + ' .bid-price, #' + item.A.e + ' .bid-bidder, #' + item.A.e + ' .bid-savings-percentage, #' + item.A.e + ' .closes-on');
							
							toAnimate.stop(true, true);
					
                            toAnimate.css('backgroundColor', 'yellow').animate( { backgroundColor: 'white' }, 800);
						   
                        }

                        if(item.A.p == 1 && item.A.i == 0){
                            auctionCountdown.text('Paused');

                            $('#' + item.A.e + ' .bid-button a').hide();
                            if($('#' + item.A.e + ' .bid-button p').text() == ''){
                                $('#' + item.A.e + ' .bid-button').append('<p>Offpeak: Resumes at 10am AEST</p>');
                            }
                        }else{
                            if(item.A.n - item.A.t > 0){
                                auctionCountdown.text(item.A.x);

                                if(item.A.l <= 10){
                                    auctionCountdown.css('color', '#ff0000');
                                }else{
                                    auctionCountdown.removeAttr('style');
                                }
                            }

                            if($('#' + item.A.e + ' .bid-button p').text()){
                                $('#' + item.A.e + ' .bid-button a').show();
                                $('#' + item.A.e + ' .bid-button p').remove();
                            }
                        }

                        if(item.A.l < 1 && item.A.o == 1){
                            auctionCountdown.text('Ended');
                            $('#' + item.A.e + ' .bid-button').hide();
                            $('#' + item.A.e + ' .bid-bookbidbutler').hide();

                        }else if(item.A.l <= 2 && item.A.o == 0){
                            auctionCountdown.text('Hurry Up');
                        }
                    });
                },

                error: function(XMLHttpRequest, textStatus, errorThrown){
                    //$('.countdown').text(textStatus);
                }
            });
        }
	 }, auctionUpdateTime);
	  
	  
	  
	setInterval(function()
	{
		//get user top bar details if logged in have pets
		if($('#BottomUserDetails').length > 0  && $('#petsInTopBar').text() > 0)
		{
			updateShownUserBids();
		}
		
	}, 7 * 1000);	
  


    // 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(1);
        bidLoading.show(1);

					
		
		
        $.ajax({ 
			cache: false,
            url: $(this).attr('href'),
            dataType: 'json',
			timeout: 1500,
            success: function(data){
                
				bidMessage.stop(true, true);
				
				var msg;
				
				if (data != null && data.Auction != null)
				{
					msg = data.Auction.message;
					
					if (data.Auction.success == true)
					{
						bidMessage.css('backgroundColor', 'green');	
					}
					else
					{
						bidMessage.css('backgroundColor', 'red');
					}
				}
				else
				{
					msg = 'Error: Session ended. Please login again.';
					bidMessage.css('backgroundColor', 'red');
				}
				
					
				bidMessage.html(msg).show(0).animate({opacity:1.0},1500).hide(0);
				
				bidButton.show(1);
                bidLoading.hide(1);
				
				if (data.Auction.success == true)
				{
					updateShownUserBids();
				}
            },
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				bidMessage.stop(true, true);
				
				var msg; 
				
				if (textStatus == 'timeout')
				{
					msg = 'Timeout: please try again.';
				}
				else if (textStatus == 'parsererror')
				{
					msg = 'Session ended. Please login again to bid.';
				}
				else
				{
					msg = 'Error - bid not registered.';
				}
				
				
				bidMessage.css('backgroundColor', 'red');
		
				bidMessage.html(msg).show(0).animate({opacity:1.0},1500).hide(0);
				
				bidButton.show(1);
				bidLoading.hide(1);
            }
        });

        return false;
    });
	
	
	$('.sponsored-refresh-button').click(function(){
												 
		var auction_id = $(this).attr('auction');
									   
		var refresh_button = $('.sponsored-refresh-button');
		var refresh_loading = $('.sponsored-refresh-loading');
		
		//hide refresh button
		refresh_button.hide();
		
		//show loading animation
		refresh_loading.css('visibility','visible');
		
		
		
		//call rsvp endpoint in ajax
		$.ajax({ 
			cache: false,
			url: $(this).attr('href'),
			dataType: 'json',
			timeout: 2999,
			success: function(data){
				
				refresh_loading.css('visibility','hidden');
			 
			   
				if(document.getElementById('sponsored-allocation'))
				{
					$('#sponsored-allocation tbody tr').remove();
					var sponsoredBalance = 0;
					
					$.each(data, function(n, tRow){
						var row = '<tr><td>' + tRow.SponsoredBid.description + '</td><td>' + tRow.SponsoredBid.modified + '</td><td style="font-weight:bold" align="right">' + (tRow.SponsoredBid.credit - tRow.SponsoredBid.debit) + '</td></tr>';
						sponsoredBalance += tRow.SponsoredBid.credit - tRow.SponsoredBid.debit;
						$('#sponsored-allocation tbody').append(row);
					});
					
					$('.sponsored-balance').text(sponsoredBalance);
					
				}
				
				refresh_button.show();
				refresh_loading.css('visibility','hidden');
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				if (textStatus == 'parsererror')
				{
					alert("Your session has ended. Please login again.");
				}
				else if (textStatus == 'timeout')
				{
					alert("Timeout detected. Please refresh the page and try again.");
				}
				else
				{
					alert(textStatus);
				}
				
				 refresh_button.show();
				 refresh_loading.css('visibility','hidden');
		
			}
		});
		
		
		
		return false;	
		
    });
	
	
	$('.sponsored-rsvp-button').click(function(){
		
		var auction_id = $(this).attr('auction');
		
		var rsvp_button = $('.sponsored-rsvp-button');
		var rsvp_loading = $('.sponsored-rsvp-loading');
		var rsvp_message = $('.sponsored-rsvp-message');
		
		rsvp_button.hide();
		rsvp_loading.css('visibility','visible');
		
		
		
		//call rsvp endpoint in ajax
		$.ajax({ 
			cache: false,
            url: $(this).attr('href'),
            dataType: 'json',
			timeout: 3500,
            success: function(data){
				
                rsvp_loading.css('visibility','hidden');
			    
				rsvp_message.stop(true, true);
				
				
				if (data != null && data.Auction != null)
				{
					if (data.Auction.success == true)
					{
						rsvp_message.css('backgroundColor', 'green');	
					}
					else
					{
						rsvp_message.css('backgroundColor', 'red');
					}
					
					rsvp_message.html(data.Auction.message).show(0).animate({opacity: 1.0}, 1500).hide(0);
				}
				else
				{
					rsvp_message.html('Error: Session ended. Please login again.').show(0).animate({opacity: 1.0}, 1500).hide(0);
					rsvp_message.css('backgroundColor', 'red');
				}
				rsvp_button.show();
				
            },
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				 rsvp_message.stop(true, true);
				 
				 rsvp_message.css('backgroundColor', 'red');
				 
				 if (textStatus == 'timeout')
				 {
                 	rsvp_message.html('Timeout: please try again.').show(0).animate({opacity: 1.0}, 1500).hide(0);
				 }
				 else if (textStatus == 'parsererror')
				 {
					rsvp_message.html('Session ended. Please login again to RSVP.').show(0).animate({opacity: 1.0}, 1500).hide(0);
				 }
				 else
				 {
					rsvp_message.html('Error - RSVP not registered.').show(0).animate({opacity: 1.0}, 1500).hide(0);
				 }
				
				 rsvp_button.show();
				 rsvp_loading.css('visibility','hidden');
		
            }
        });
		
		
		//show success msg to user if success
		
		return false;						   
	});
	 
	 /*
	$('.sponsored-survey-button').click(function(){
		
		//load up survey... 
		
		
		//on close success
		//updateSponsoredBids($(this).attr('auction'));
	});
	*/
	 
	 
	 

    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');
        });
    }

});
