$(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: 2000,
                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(item.LastBid.username == 'Hamarosan indul!' || item.LastBid.username == 'Még nem érkezett licit!') {
							$('#' + item.Auction.element + ' .bidder').html('<br />');
						}

                        if(auctionEndTime != item.Auction.end_time){
                            auctionCountdown.attr('title', item.Auction.end_time);

                            $('#' + item.Auction.element + ' .bid-price').html(item.Auction.start_price);
                            if($('#bidHistoryTable').text()){
								if ( $('#bidHistoryTable').attr('title') == $('#' + item.Auction.element).attr('title') ) {								
								
									if(document.getElementById('uid')){
										if(document.getElementById('uid').value == item.LastBid.id) {
											var used_price = parseInt(document.getElementById('used_price').value)+(100)*1;
											var start_price = item.Auction.rrp;
											start_price = start_price.replace(" ", "");
											start_price = start_price.replace(".", "");
											start_price = start_price.replace(",", "");											
											start_price = start_price.replace("Ft", "");
											parseInt(start_price);
											var actual_price = start_price-used_price;
											if (actual_price < 0) {
												actual_price = 0;
											}
											$('#used_price').attr('value',used_price);
											$('#bid-used-price').html(used_price);
											$('#bid-used-price').format({format:'## ### Ft', locale:'hu'});																						
											$('#bid-actual-price').html(actual_price);											
											$('#bid-actual-price').format({format:'## ### Ft', locale:'hu'});																					
										}
									}																		
								
									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);
									
									$(' .bid-savings-price-table').html(item.Auction.savings.price); //
									$(' .bid-price-table').html(item.Auction.start_price); //
								}
                            }
							$('#' + item.Auction.element + ' .countdown').animate( { backgroundColor: '#ff4100', color: '#ffffff' }, 500).animate( { backgroundColor: '#ffffff', color: '#000044' }, 1000);
							$('#' + item.Auction.element + ' .bid-price').animate( { color: '#ff4100' }, 500).animate( { color: '#66bc29' }, 1000);
                        }

                        if(item.Auction.peak_only == 1 && item.Auction.isPeakNow == 0){
                            auctionCountdown.text('Szünetel');
                            $('#' + item.Auction.element + ' .bid-button a').hide();
                            if($('#' + item.Auction.element + ' .bid-button p').text() == ''){
                                $('#' + item.Auction.element + ' .bid-button').append('<p>9:00-tól 24:00-ig</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');
									$('#'+item.Auction.element).animate( { backgroundColor: '#f1f1f1' }, 500).animate( { backgroundColor: 'white' }, 500);
                                }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('Lezárult');
                            $('#' + item.Auction.element + ' .bid-button').hide();
                            $('#' + item.Auction.element + ' .bid-bookbidbutler').hide();
                        }
						
						if(item.Auction.future == 1){
							$('#' + item.Auction.element + ' .countdown').html('<br />');
							$('#' + item.Auction.element + ' .countdown-bid').html('<br />');
						}
						
                    });
                },
                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(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);
                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;
        });
    }

});