function getAuctions(){
    var auctions='';
    $('.auctionCategorys:visible .auction-item').each(function(){
        var auctionId    = $(this).attr('id');
        var auctionTitle = $(this).attr('id').substring(8);
        var counter      = $('#' + auctionId + ' .countdownTimestamp');       
        if(counter){
        	if(counter.html()+10 > fetchTimestamp()){
        		auctions = auctions + auctionId + '=' + auctionTitle + '&';
          }
        }
    });
    return auctions;
}

$(document).ready(function(){
     
     var el1 = $('.auction-imgBg');
     $(el1).hover(
      function () {
        $(this).find('.INFO').css('background-color','#999');
      },
      function () {
        $(this).find('.INFO').removeAttr('style');
      }
    );



    $('.helpUL div').toggle();
    $('.helpUL a').css('cursor','pointer').click(function(){$(this).next().toggle();});
    if($.browser.msie){
        //Configuring ajax
        $.ajaxSetup({
            cache: false
        });
    }

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

    // 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
    /*
    
    */
    


    // Main countdown for updating auction and flashing
    setInterval(function(){
        var auctions = getAuctions();
        if(auctions=='' && $('#end-auctions').length==0){
          $('.auction-item').each(function(){
              var auctionId    = $(this).attr('id');
              var auctionTitle = $(this).attr('id').substring(8);
              //var auctionTitle = $(this).attr('title');
              var counter      = $('#' + auctionId + ' .countdownTimestamp');

              if(counter){
                if(counter.html() > fetchTimestamp()){

                  auctions = auctions + auctionId + '=' + auctionTitle + '&';

                  }
              }
          });
        }
        if(auctions){

        	var nocacheTimestamp = new Date();

            if($('.bid-histories').length > 0){
                getStatusUrl = '/getstatus.php?histories=yes&time='+nocacheTimestamp.getTime();
            }else{
                getStatusUrl = '/getstatus.php?time='+nocacheTimestamp.getTime();
            }
            $.ajax({
                url: getStatusUrl,
                dataType: 'json',
                type: 'POST',
                timeout: 4999,
                global: false,
                data: auctions,
                success: updateAuctions,

                error: function(XMLHttpRequest, textStatus, errorThrown){
                }
            });
        }
    }, auctionUpdateTime);

    // Function for bidding
    $('.bid-button-link').click(function(){
    	var auctionElement = 'auction_' + $(this).attr('id').substring(16);
        var bidButton      = $('#' + auctionElement + ' .bid-button');
        var bidLoading     = $('#' + auctionElement + ' .bid-loading');
        var bidMessage     = $('#' + auctionElement + ' .bid-message');


        bidButtonSRC=$('#' + auctionElement + ' .bid-button .bid-button-link img').attr('src');
        bidLoadingSRC=$('#' + auctionElement + ' .bid-loading  img').attr('src');
        BidButtonClass=$('#' + auctionElement + ' .bid-button .bid-button-link img').attr('class');

        $('#' + auctionElement + ' .bid-button .bid-button-link img').attr('src',bidLoadingSRC);
        $('#' + auctionElement + ' .bid-button .bid-button-link img').attr('class','');
        $('#' + auctionElement + ' .bid-button .noteButton').css('display','none');

        $.ajax({
            url: $(this).attr('href'),
            dataType: 'json',
            success: function(data){
            $('#' + auctionElement + ' .bid-button .bid-button-link img').hide(1).animate({opacity: 1.0}, 5000).show(1,function(){
                    $('#' + auctionElement + ' .bid-button img').removeAttr('style')
                    $('#' + auctionElement + ' .bid-button .noteButton').removeAttr('style')
                });
        		bidMessage.html(data.Auction.message).show(1).animate({opacity: 1.0}, 5000).hide(1);
        		$('#' + auctionElement + ' .bid-button .bid-button-link img').attr('src',bidButtonSRC);
        		$('#' + auctionElement + ' .bid-button .bid-button-link img').attr('class',BidButtonClass);
        		$('#' + auctionElement + ' .bid-button .bid-button-link img').css('display','inline');
            }
        });

        return false;
    });

    if($('.productImageThumb').length){
        $('.productImageThumb').click(function(){
            if($('#productImageMax').css('display')=='none'){$('#productImageMax').toggle();}
            //if($('#technicalDescription').css('display')=='block'){$('#technicalDescription').toggle();}

            $('.productImageMax').fadeOut('fast').attr('src', $(this).attr('href')).fadeIn('fast');
            return false;
        });
        $('#productImageMax').click(function(){
        });
        $('.closeBut img').css('cursor','pointer');
        $('.closeBut img').click(function(){
            $('#productImageMax').toggle();
            $('#technicalDescription').toggle();
        });
    }
    if($('.productImageThumbBN').length){
       $('.productImageThumbBN').click(function(){
             $('.productImageMaxBN').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');
        });
    }

});

function updateAuctions(data){
    var chColor='#5e3f12';
    $.each(data, function(i, item){
        if(item.Auction.bid_allow!=1 && item.Auction.closed!=1)
        {

          var text = $('#timer-text').val();
          //time-remaining

          $('#' + item.Auction.element + ' .time-remaining').html("Time to beginning");
          $('#' + item.Auction.element + ' .bid-status').html(text);
          $('#' + item.Auction.element + ' .bid-bidder').html(item.Auction.start_time);
          return;
        }
        if(item.Auction.closed==1)
        {
          var text = $('#end-text').val();
          $('#' + item.Auction.element + ' .bid-status').html(text);
          $('#' + item.Auction.element + ' .bid-button').css("display","none");
          $('#' + item.Auction.element + ' .bid-bidder').html($('#winner-text').val()+" "+item.LastBid.username);
          var size = $('#' + item.Auction.element + ' .bid-bidder').css("font-size");
          if(size.substring(0,(size.length) - 2))
          {
            $('#' + item.Auction.element + ' .bid-bidder').css("font-size","15px");
          }

          return;
        }

        $('#' + item.Auction.element + ' .bid-button').css("display","block");
        var auctionBlock        = $('#' + item.Auction.element);
        var auctionEndTime      = $('#' + item.Auction.element + ' .countdownTimestamp').html();
        var auctionLatestBidder = $('#' + item.Auction.element + ' .bid-bidder').text();
        var auctionCountdown    = $('#' + item.Auction.element + ' .countdown');
        var auctionClosesOn     = $('#' + item.Auction.element + ' .closes-on');

        var biduser = item.LastBid.username;
        if(biduser=='No bids yet'){biduser=$('#user-text').val();}
        $('#' + item.Auction.element + ' .bid-bidder').html(biduser);

        if(item.Histories.length>0){

          /*
          var tbody =$('.biddingHistory table tbody');
          $('.biddingHistory table tbody tr td').css('background-color','');
          tbody.prepend('<tr><td style="padding-left: 20px;background-color:#BFA35C;" >'+item.Auction.start_price+'</td><td style="background-color:#BFA35C;">'+item.LastBid.username+'</td></tr>');
          $('.biddingHistory table tbody tr:last').remove();
          */
          var count = 1;
          var histFirstLine ='background-color:#BFA35C;'
          $('.biddingHistory table tbody').html('');
          $.each(item.Histories, function(n, tRow){
                if(count>1){
                    histFirstLine = '';
                }
                var row = '<tr><td style="padding-left: 20px;'+histFirstLine+'" >' + tRow.Bid.price + '</td><td style="'+histFirstLine+'">' + tRow.Bid.username + '</td></tr>';
                $('.biddingHistory table tbody').append(row);
                count++;
            });

        }



        if(auctionEndTime != item.Auction.end_time && (item.Auction.isPeakNow !=0 || item.Auction.peak_only !=1)){

            

            $('#' + item.Auction.element + ' .countdownTimestamp').html(item.Auction.end_time);
            if(document.getElementById('bidHistoryTable' + item.Auction.id)){
                if($('#bidHistoryTable' + item.Auction.id + ' p').text()){
                    $('#bidHistoryTable' + item.Auction.id + ' p').remove();
                }
                $('#bidHistoryTable' + item.Auction.id + ' 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' + item.Auction.id + ' 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);

            }

            if($("#countdownColor").length == 0){

                var bidbidderColor =  $('#' + item.Auction.element + ' .bid-bidder').css("color");
                var bidpriceColor =  $('#' + item.Auction.element + ' .bid-price').css("color");
                var countdownColor =  $('#' + item.Auction.element + ' .countdown').css("color");


                $('#contInner').prepend('<input type="hidden" id="bidbidderColor"  value="'+bidbidderColor+'"/>');
                $('#contInner').prepend('<input type="hidden" id="bidpriceColor"   value="'+bidpriceColor+'<"/>');
                $('#contInner').prepend('<input type="hidden" id="countdownColor"  value="'+countdownColor+'<"/>');

            }
            var countdownColorOrg = $('#countdownColor').val();
            var bidpriceColorOrg = $('#bidpriceColor').val();
            var bidbidderColorOrg = $('#bidbidderColor').val();
            $('#' + item.Auction.element + ' .countdown').animate( { color: chColor }, 100).animate( { color: countdownColorOrg }, 200);
            $('#' + item.Auction.element + ' .bid-price').animate( { color: chColor }, 100).animate( { color: bidpriceColorOrg }, 200);
            $('#' + item.Auction.element + ' .bid-bidder').animate( { color: chColor }, 100).animate( { color: bidbidderColorOrg }, 200);
        }else if(item.Auction.isPeakNow ==0 && item.Auction.peak_only ==1){
            auctionCountdown.text($('#peakText').val());
        }else{
            
        }

        $('#' + item.Auction.element + ' .bid-price').html(item.Auction.start_price);
        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() == ''){
                var peakText = $('#peakTextB').val();
                $('#' + item.Auction.element + ' .bid-button').append('<p style="line-height: 15px; font-size:12px;">'+peakText+'</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('Paused');
        }



    });
}





///########################################################################################
///########################################################################################
///########################################################################################
$(document).ready(function(){
 var buttons = $('.noteButton');
 for(var i=0;i<buttons.length;i++)
 {
    if(buttons[i].getAttribute("id") != null && buttons[i].getAttribute("id") != "")
    {

        var id=buttons[i].getAttribute("id").substring(11);

         $("#noteButtonValue_"+id).click(function(){$("#noteButtonValue_"+this.id.substring(16)).hide();});
        $('#noteButton_'+id).click(function(){
        $("#noteButtonValue_"+this.id.substring(11)).toggle();

        });

    }


 }
});
function innerContMenue(el,img){


   var path = $('#innerTopBgImg1').attr('src');
   $('#innerTopBgImg0').attr('src',path);
   path = path.substr(0,path.lastIndexOf('/')+1);
   path = path+'start_'+img+'.jpg';
   $('#innerTopBgImg1').attr('src',path);
   $('#innerTopBgImg1').css("opacity","0");
   $('#innerTopBgImg1').animate({
        opacity: 1
      }, 1500 );

}
function catButton(el){
  $('#live-auctions').show();
  $('#auction-tabs a').removeClass('selected');
  $('.auctionCategorys').hide();
  $('#end-auctions').hide();
  $('#category_'+el).toggle();

}
function getEndedAuctions(page){

    var url='/auctions/endedAuctions/'+page;
    $.ajax({
            url: url,
            dataType: 'json',
            success: showEndedAuctions
        });
        return false;

}
function showEndedAuctions(data){
    
    // Content leeren
    var cont = $('#end-auctions table tbody');
    cont.html('');
    var pannel = '';
    pannel+=('<tr>');

    $.each(data, function(i, item){
            
            
       if(item.Auction!=null){
            //alert(5 % i);
            if((i % 5) === 0){
                pannel+='</tr><tr>';
            }

        
            pannel+= '<td  class="auction-item">';
            pannel+=    '<div class="auctionBg" >';
            pannel+=       '<div class="auction-imgBg">';
            pannel+=          '<div class="text title">';                                                                                                                                                                
            pannel+=             '<a href="/auctions/view/'+item.Auction.id+'" class="black">';
            if(item.Auction.title!=null && item.Auction.title.indexOf('<br/>')!=-1){
            var title = item.Auction.title.split('<br/>');
            pannel+=                '<span style="font-size:105%;" class="bold">'+title[0]+'</span>';
            pannel+=                   '<br/>';
            pannel+=                 '<span style="font-weight: normal">'+title[1]+'</span>';
            }else{
            pannel+=                '<span style="font-size:105%;" class="bold">'+item.Auction.title+'</span>';
            }
            pannel+=             '</a>';
            pannel+=          '</div>';
            pannel+=          '<div>';
            pannel+=            '<a href="/auctions/view/'+item.Auction.id+'">';
            pannel+=               '<img src="/img/auction_images/thumbs/'+item.Auction.image+'" class="auctionImage" onerror="this.src=\'/img/auction_images/thumbs/no-image.gif\'" alt="" />';
            pannel+=            '</a>';
            pannel+=          '</div>';
            pannel+=        '</div>';
            pannel+=        '<div  class="textb bid-status countdown">';
            pannel+=           item.Auction.end_time;
            pannel+=        '</div>';
            pannel+=        '<div class="price-bidder bid-price align-left">';
            pannel+=           item.Auction.price;
            pannel+=        '</div>';
            pannel+=        '<div class="auction-winner bid-bidder">';
            pannel+=            item.Auction.winner;
            pannel+=        '</div>';
            pannel+=        '<div class="bid-now">';
            pannel+=        '<div class="bid-button">';
            pannel+=        '</div>';
            pannel+=       '</div>';
            pannel+=       '<div>';
            pannel+=         '<div class="bid-message-wrapper">';
            pannel+=           '<div class="bold red bid-message"></div>';
            pannel+=           '</div>';
            pannel+=       '</div>';
            pannel+=    '</div>';
            pannel+= '</td>';
       
       }else if(item.navi!==null){
          showEndedNavi(item.pages,item.start);          
       }
            
            
    });
    pannel+='</tr>';
    cont.append(pannel);
    
}
function showEndedNavi(pages,start){
   // Navi leer machen
   var nav = $('#endedNavi');
   var button = '';
   var x = true;
   var y = true;
   
   nav.html('');

   if(pages>10){
       //button+='<a onclick="getEndedAuctions(1)" >1</a>';
       for(var i=0;i<pages;i++){
           var cl = '';
           if(start==(i+1)){
               cl='endedActive';
           }
           if(i==0){
             button+='<a class="'+cl+'" onclick="getEndedAuctions(1)" >1</a>';  
           }
           if(start<i+7 && start>i-7){
              if(i!=0 && i+1!=pages){
                 button+='<a class="'+cl+'" onclick="getEndedAuctions('+(i+1)+')" >'+(i+1)+'</a>';
              }

           }else if(x){
              x=false;
              button+=' ...';
           }
           if(start<i-7 && y){
              y=false;
              button+='... ';
           }
           if(i+1==pages){
               button+='<a class="'+cl+'" onclick="getEndedAuctions('+(pages)+')" >'+(pages)+'</a>';
           }
       }
      
   }else{
       for(i=0;i<pages;i++){

           var cl = '';
           if(start==(i+1)){
               cl='endedActive';
           }
           button+='<a class="'+cl+'" onclick="getEndedAuctions('+(i+1)+')" >'+(i+1)+'</a>';
       }
   }
   nav.append(button);

}