$(document).ready(function(){
    if($.browser.msie){
        //Configuring ajax
        $.ajaxSetup({
            cache: false
        });
    }

    fetchTimestamp = function(){
        return parseInt($('#timestamp').text());
    };

    // Default frequency for auction updating and time sync
    var auctionUpdateTime = 10;
	
    if($('#auctionupdatefrequency').text()){
        auctionUpdateTime = parseInt($('#auctionupdatefrequency').text());
    }

    // Convert it to milisecond
    //auctionUpdateTime = auctionUpdateTime * 1000;
    auctionUpdateTime = auctionUpdateTime * 900;

    // 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');

        if($('#' + auctionId + ' .countdown').length){
            if($('#' + auctionId + ' .countdown').attr('title') > fetchTimestamp()){
                auctions = auctions + auctionId + '=' + auctionTitle + '&';
            }
        }
    });

    // Main countdown for updating auction and flashing
    setInterval(function(){
        if(auctions){
            if(document.getElementById('bidHistoryTable')){
                getStatusUrl = '/auctions/getstatus/yes';
            }else{
                getStatusUrl = '/auctions/getstatus';
            }

            $.ajax({
                url: getStatusUrl,
                dataType: 'json',
                type: 'POST',
                data: auctions,
                success: function(data){

                    $.each(data, function(i, item){
					//alert(item.Auction.id);
                        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 prefixa='370';
							if(item.LastBid.username.substring(0,3)==prefixa)
							{
								var laima="+"+item.LastBid.username.substring(0,(item.LastBid.username.length-3))+"**";
							}
							else
							{
								var laima=item.LastBid.username;
							}
                       if(auctionLatestBidder != laima){
							//alert(item.LastBid.username.substring(0,3));
							var prefix='370';
							if(item.LastBid.username.substring(0,3)==prefix)
							{
							//alert(item.LastBid.username.length-3);
							item.LastBid.username="+"+item.LastBid.username.substring(0,(item.LastBid.username.length-3))+"**";
							}
							
							//var jqueris = $('#' + item.Auction.element+ ' .bid-bidder');	
							//alert($('#' + item.Auction.element + ' .bid-bidder').html());
                            $('#' + item.Auction.element + ' .bid-bidder').html(item.LastBid.username);
							
							laima="";
                        }
						
                        if(auctionEndTime != item.Auction.end_time){
                            auctionCountdown.attr('title', item.Auction.end_time);

                            $('#' + item.Auction.element + ' .bid-price').html(item.Auction.start_price);
                            $('#' + item.Auction.element + ' .bid-savings-percentage').html(item.Auction.savings.percentage);
                            $('#' + item.Auction.element + ' .bid-savings-price').html(item.Auction.savings.price);

                            if(document.getElementById('bidHistoryTable')){
                                if($('#bidHistoryTable p').text()){
                                    $('#bidHistoryTable p').remove();
                                }

                                $('#bidHistoryTable tbody tr').remove();

                                $.each(item.Histories, function(n, tRow){
									var prefixx='370';
							if(tRow.User.username.substring(0,3)==prefixx)
							{
							//alert(item.LastBid.username.length-3);
							var laimii="+"+tRow.User.username.substring(0,(tRow.User.username.length-3))+"**";
							}
							else
							{
							 var laimii=tRow.User.username;
							}
                                    var row = '<tr><td>' + tRow.Bid.created + '</td><td>' + laimii + '</td><td>' + tRow.Bid.description + '</td></tr>';

                                    $('#bidHistoryTable tbody').append(row);
                                });
                            }

                            if(auctionLatestBidder != 'Latest Bidder'){
                                $('#' + item.Auction.element + ' .countdown, #' + item.Auction.element + ' .bid-price, #' + item.Auction.element + ' .bid-bidder, #' + item.Auction.element + ' .bid-savings-percentage').animate( { backgroundColor: 'yellow' }, 500).animate( { backgroundColor: 'white' }, 1000);
                            }
                        }

                        if(item.Auction.peak_only == 1 && item.Auction.isPeakNow == 0){
                            auctionCountdown.text('Sustabdytas iki 9:00');

                            $('#' + item.Auction.element + ' .bid-button a').hide();
                            if($('#' + item.Auction.element + ' .bid-button p').text() == ''){
                                $('#' + item.Auction.element + ' .bid-button').append('');
                            }
                        }else{
							if(item.Auction.end_time - item.Auction.serverTimestamp > 0){
								$('#' + item.Auction.element + ' .bid-button').show();
                                auctionCountdown.text(item.Auction.end_time_string);
                            }

                            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.end_time - item.Auction.serverTimestamp <= 0)
			{
				// auctionCountdown.text('Tikrinama '+item.Auction.end_time+' '+item.Auction.serverTimestamp);
				auctionCountdown.text('Tikrinama');
				$('#' + item.Auction.element + ' .bid-button').hide();
				$('#' + item.Auction.element + ' .bid-bookbidbutler').hide();
				if(item.Auction.closed==1)
				{
					auctionCountdown.text('Pasibaigęs');
					$('#' + item.Auction.element + ' .captcha').hide();
				}
			}
			else
			{

			}
						
                    });
                }
            });
        }
    }, auctionUpdateTime);

    // Function for bidding
    $('.bid-button-link').click(function(){
        var auctionId         = $(this).parent().parent().parent().attr('title');
		var auctionIdas         = $(this).parent().parent().parent().attr('id');
        var bidMessage        = $(this).parent().parent().parent().children('.bid-message');
        var bidButton         = $(this).parent().parent().children('.bid-button');
        var bidLoading        = $(this).parent().parent().children('.bid-loading');

       // alert(auctionId);
        bidButton.hide(1);
        bidLoading.show(1);
		var kodas='';
		kodas=$("#code_"+auctionIdas).attr("value");
		if(kodas === undefined)
		{
			kodas='';
		}
		else
			kodas='/'+kodas;

		var raktas='';
		raktas=$("#key_"+auctionIdas).attr("value");
		if(raktas === undefined)
		{
			raktas='';
		}
		
				
		
		//$("#code").attr("value")
		//alert(($(this).attr('href'))+'/'+($("#code").attr("value")));
		//alert($(this).attr('href')+kodas);
        $.ajax({
            url: ($(this).attr('href')+kodas),
            dataType: 'json',
			type: 'GET',
            success: function(data){
                bidMessage.html(data.Auction.message).show(1).animate({opacity: 1.0}, 2000).hide(1);
                bidButton.show(1);
                bidLoading.hide(1);
				$("#imagec_"+auctionIdas).attr("src","http://www.telebid.lt/securimage/securimage_show.php?sid="+Math.random()+"&aid="+auctionId+"&key="+raktas);
				//alert($("#imagec_"+auctionIdas).attr("src"));
				$("#msg").html(data.Auction.message);
				$("#code_"+auctionIdas).attr("value","");
            }
        });

        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');
        });
    }

});

