$(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 * 500;

    // 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){
			var randnum = Math.floor(Math.random()*10000);

            if($('#bidHistoryTable').length){
                getStatusUrl = '/getstatus_directdb.php?histories=yes&time='+nocacheTimestamp.getTime()+randnum;
                //getStatusUrl = '/getstatus_client.php?histories=yes&time='+nocacheTimestamp.getTime(); //+randnum;
                //getStatusUrl = '/getstatus.php?histories=yes&time='+nocacheTimestamp.getTime()+randnum;
            	//getStatusUrl = '/auctions/getstatus/yes';
            }else{
            	getStatusUrl = '/getstatus_directdb.php?time='+nocacheTimestamp.getTime()+randnum;
                //getStatusUrl = '/getstatus_client.php?time='+nocacheTimestamp.getTime(); //+randnum;
                //getStatusUrl = '/getstatus.php?time='+nocacheTimestamp.getTime()+randnum;
            	//getStatusUrl = '/auctions/getstatus/';
            }

            $.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("Nyerésre áll: "+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><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-bidder, #' + item.Auction.element + ' .bid-savings-percentage, #' + item.Auction.element + ' .closes-on').animate( { backgroundColor: 'yellow' }, 500).animate( { backgroundColor: 'white' }, 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>Klasszikus licit</p>');
                            }
                        }else{
                            if(item.Auction.end_time - item.Auction.serverTimestamp > 0){
                                auctionCountdown.text(item.Auction.end_time_string);

                                if(item.Auction.time_left <= 11){
                                    auctionCountdown.css('color', '#ff0000');
                                    // TO MR MATZON MAESTRO:
                                    // Itt tudod megadni, hogy 10 SEC alatt milyen legyen a színe 
                                    // keretnek stb...
                                }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('Elkelt');
                            $('#' + 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:00');
                            $('#' + item.Auction.element + ' .bid-button').hide();
                            $('#' + item.Auction.element + ' .bid-bookbidbutler').hide();
                        } else {
                        	$('#' + item.Auction.element + ' .bid-button').show();
                            $('#' + item.Auction.element + ' .bid-bookbidbutler').show();
                        }
                    });
                },

                error: function(XMLHttpRequest, textStatus, errorThrown){
                   // $('.countdown').text(textStatus);
                }
            });
        }
    }, auctionUpdateTime);

	function updateUserBalance(){
		//Null
		$('.balance').html("3");
		//alert('');
	};

    // 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 userBalance	   = $('.balance');

		var marketprice    = $('.mp');
		var deliverycost   = $('.dc');
        var savedofmybids  = $('.somb');		
        var priceforme     = $('.pfm');
        var totalprice     = $('.tpr');
		
        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);
                userBalance.html(data.Auction.balance);

		        marketprice.html(data.Auction.mp);
		        deliverycost.html(data.Auction.dc);
                savedofmybids.html(data.Auction.somb);
                priceforme.html(data.Auction.pfm); 
                totalprice.html(data.Auction.tpr); 
        		bidLoading.hide(1);
                bidButton.show(1);
            }
        });

        return false;
    });

    // Function for buying
    $('.buy-button-link').click(function(){
        var auctionElement = 'auction_' + $(this).attr('title');
        var buyButton      = $('#' + auctionElement + ' .buy-button');
        var buyLoading     = $('#' + auctionElement + ' .buy-loading');
        var buyMessage     = $('#' + auctionElement + ' .buy-message');
		var userBalance	   = $('.balance');

        buyButton.hide(1);
        buyLoading.show(1);
        $.ajax({
            url: $(this).attr('href'),
            dataType: 'json',
            success: function(data){
                buyMessage.html(data.Auction.message).show(1).animate({opacity: 1.0}, 2000).hide(1);
                userBalance.html(data.Auction.balance);
                buyLoading.hide(1);
                buyButton.show(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');
        });
    }

});

