/******************************
 *
 * PROCESS BIDING
 *
 ******************************/
var $dictionary;

/***** na(t)ive functions *****/
function str_replace(search, replace, subject) {
    var s = subject;
    var ra = r instanceof Array, sa = s instanceof Array;
    var f = [].concat(search);
    var r = [].concat(replace);
    var i = (s = [].concat(s)).length;
    var j = 0;

    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }

    return sa ? s : s[0];
}

function in_array (needle, haystack) {

    for (key in haystack) {
        if (haystack[key] == needle) {
            return true;
        }
    }

    return false;
}

/***** end of native functions *****/

function bindFutureClickForBid()
{
	$('div.nubieden_gray_small').unbind('click');
	$('div.nubieden_gray').unbind('click');
	

	$('div.nubieden_gray_small').bind('click', function() {
		showInfo($dictionary.get('info_this_is_a_future_auction'));
	});
	
	$('div.nubieden_gray').bind('click', function() {
		showInfo($dictionary.get('info_this_is_a_future_auction'));
	});	
	
}

function bindClickForBid()
{
	$('div.bidMe').unbind('click');

	$('div.bidMe').bind('click', function() {
		$bidder.bidMe($(this).parent().parent('.activeOfr').attr('id'));
	});
}


function bindClickForMultiBid()
{
	$('div.multiBidMe').unbind('click');
	
	$('div.multiBidMe').bind('click', function() {
		
		var auctionID;
		
		if ( $(this).parent().parent().parent('.activeOfr').length )
		{
			auctionID = $(this).parent().parent().parent('.activeOfr').attr('id');
		}
		else if ( $(this).parent().parent('.activeOfr').length )
		{
			auctionID = $(this).parent().parent('.activeOfr').attr('id');
		}
		
		
		$bidder.multiBidMe(auctionID ,
                           $(this).parent().children('.bidUserValue').children('.userProposal').attr('value')
		);
		//$('div.multiBidMe').unbind('click');

	});
}

function showInfo($message)
{
	if ($('.messenger').html() != "")
	{
		$('.messenger').remove();
	}

	$('#container').prepend('<div class="messenger" style="display:none"><div class="msg">' + $message + '</div></div>');
	$('.messenger').fadeIn();
	setTimeout(function() { $('.messenger').fadeOut(function(){$(this).remove(); }); }, 2000);

}

function formatCurrency(num)
{
	if (num != undefined)
	{
		num = num.toString().replace(/\$|\,/g,'');

		if(isNaN(num))
		{
			num = "0";
		}

		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();

		if(cents < 10)
		{
			cents = "0" + cents;
		}

		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		{
			num = num.substring(0,num.length-(4*i+3))+'.'+ num.substring(num.length-(4*i+3));
		}

		return (num + ',' + cents);
	}
	else
	{
		return '0,00';
	}


}

Bidder = function()
{
	this.currentTimeSpinnerId = -1;
	this.ajaxFlag = 0;

    this.errorStatuses = new Array(-2, -1, 0, 2, 3, 7);
    this.bidErrorStatuses = new Array(3, 9, 10, 11, 12, 13, 15, 16, 99);

	/*
	 * get active auctions as string
	 */
	this.getActiveAuctions = function($excludeFuture)
	{
		// get active auctions
		$data = $('.activeOfr');

		$req = "";

		// create req string from ids
		$data.each(function() {
            if (!$excludeFuture || ($excludeFuture && !$(this).hasClass('futureOfr')))
            {
                $req += $(this).attr('id') + ",";
            }

		});

		//remove unnecessery coma
		$req = $req.substring(0, $req.length-1);

		return $req;
	};

	/*
	 * get futuw auctions as string
	 */
	this.getFutureAuctions = function()
	{
		// get active auctions
		$data = $('.futureOfr');

		$freq = "";

		// create req string from ids
		$data.each(function() {
            $freq += $(this).attr('id') + ",";
		});

		//remove unnecessery coma
		$freq = $freq.substring(0, $freq.length-1);

		return $freq;
	};




	/*
	 * check status of auctions
	 */
	this.checkStatus = function()
	{

		obj = this;

		$activeAuctions = this.getActiveAuctions();
		$futureAuctions = this.getFutureAuctions();

		if (this.ajaxFlag == 0)
		{
			this.ajaxFlag = 1;
			// get json response
			$.getJSON("/processor/get-status/", "a=" + $activeAuctions + "&fa=" + $futureAuctions, function(json)
			{
				 // update auctions status
				jsonData = json;
				obj.updateStatus(json);
			});
		}
	};

	/*
	 * update auctions visualizations
	 */
	this.updateStatus = function($response)
	{
		// pass through json object
		$response = eval($response);

		// update user credits view
		if ( !in_array($response, obj.errorStatuses) )
		{
			for ($r in $response)
			{
				$newPrice = parseFloat($response[$r].price);
				$oldPrice = parseFloat($('#' + $r + " .price label").html());

				$('#' + $r + " .price label").html( formatCurrency( $response[$r].price ) );
                
/*              TURNED OFF  // set price in insert price box (multiitem)
                if ($('#' + $r + " .userProposal").length > 0 && ! $('#' + $r + " .userProposal").hasClass('focus') && $('#' + $r + " .userProposal").val() <= $response[$r].price)
                {
                    $('#' + $r + " .userProposal").val(  $response[$r].price );
                }
*/
				$('#' + $r + " .actual_bidded_price").html( '&euro; '+str_replace('.', ',', $response[$r].price) );
				$('#' + $r + " .last_bidder label").html($response[$r].highest);
				$('#' + $r + " .time label").html($response[$r].time);
				$('#' + $r + " .time label").attr('class',$response[$r].cssClass);
				$('#' + $r + " label.bidCost").html($response[$r].bidCost);
				$('#' + $r + " label.bidValue").html( str_replace('.', ',', $response[$r].bidValue) );

			}

			// update history of bids (on show screen)
			if ($('#auction-show').length > 0 || $('#auction-simple-show').length > 0 )
			{
				// switch to inactive
				if($response && $response['auctions_to_remove'] && $response['auctions_to_remove'][0])
				{
					window.location.reload();
					return true;
//					$atrid = $response['auctions_to_remove'][0];
//					$('#' +  $atrid + " .time").html('<span class="status_finished">Beëindigd</span>');
//					$('#' +  $atrid).attr('class', 'offer_bids');
//					//$('#' +  $atrid + " .nubieden").attr('class', 'nubieden_none');
				}

				obj.updateHistory($response);
			}

			// make some auction list things
			if ($("#auction-all").length > 0)
			{
				for($a in $response['future_to_remove'])
				{
					$futureId = $response['future_to_remove'][$a];
					$('#' +  $futureId).remove();
				}
				// put finished auction to proper section
				for($a in $response['auctions_to_remove'])
				{
					window.location.reload();
					return true;
					
//					$atrid = $response['auctions_to_remove'][$a];
//
//					$('#' +  $atrid + " .time label").html('Beëindigd');
//					$('#' +  $atrid + " .time").attr('class', 'time');
//					$('#' +  $atrid).attr('class', 'offer');
//
//					(function($atrid){
//					// get finished auction template
//					$.ajax({
//						  type: "POST",
//						  url: "/auction/get-auction-list",
//						  data: "id=" + $atrid,
//						  success: function($msg)
//						  {
//                             // for multiitem auction
//                             //$('#' +  $atrid + " .multibid").attr('class', '');
//                             //$('#' +  $atrid + " .bidUserValue").remove();
//                             // for common stuff
//							 //$('#' +  $atrid + " div:last").attr('class', 'additional_info');
//							 //$('#' +  $atrid + " div:last").html($msg);
//						  }
//						});
//					})($atrid);
				}
			}

			// make some first page content things
			if ($('#index-index').length > 0)
			{

				if($response && $response['auctions_to_remove'] && $response['auctions_to_remove'][0])
				{
					window.location.reload();
					return true;
				}

//				for($a in $response['future_to_remove'])
//				{
//					$futureId = $response['future_to_remove'][$a];
//					$('#' +  $futureId).remove();
//				}
				// put finished auction to proper section
//				for($a in $response['auctions_to_remove'])
//				{
//					window.location.reload();
//					return true;

//					$atrid = $response['auctions_to_remove'][$a];
//					$('#' +  $atrid + " .time label").html('--:--:--');
//
//					//console.log( $(this).hasClass('futureOfr') )
//					$('#' + $atrid).fadeOut(function()
//					{
//						// get finished auction template
//						$.ajax({
//							  type: "POST",
//							  url: "/auction/get-auction",
//							  data: "id=" + $(this).attr('id'),
//							  success: function($msg)
//							  {
//								$('#last_bought .finished div.offer:last').remove();
//								$('#last_bought .finished').prepend($msg);
//							  }
//							});
//
//						// if we process special auction, remove header and put ad
//						if ($(this).parent().attr('id') == 'speciale_offer')
//						{
//							$(this).parent().children('.block_header').remove();
//
//							$.ajax({
//								  type: "GET",
//								  url: "/processor/get-advert",
//								  success: function($msg)
//								  {
//									$('#speciale_offer').prepend($msg);
//								  }
//								});
//						}
//
//						$(this).remove();
//					});
//				}
			}
		} else {
			this.messenger($response);
		}

		this.ajaxFlag = 0;

	};

	this.refreshHistory = function($auctionId)
	{
		$("#bidding_history table").load("/processor/get-history/?a="+$auctionId);
	}
	
	/*
	 * update visual history of bids
	 */
	this.updateHistory = function($response)
	{
		obj = this;
		$container = $('#bidding_history table');
		if ($container.length == 1)
		{
			for ($r in $response)
			{
                $oldPrice = $('#bidding_history table tr:first label strong').html();
                
				$oldPrice = str_replace(',', '.', $oldPrice);
				$newPrice = str_replace(',', '.', $response[$r].price);
			    //console.log(parseFloat($oldPrice));
				
				// if element is object and price was changed, update history
				if (typeof($response[$r]) == 'object' && $response[$r].not_real == 0 && (($newPrice != $oldPrice) || ($response[$r].highest != '-----' && parseFloat($newPrice) > 0 && $oldPrice == null)))
				{

					if(parseFloat($newPrice) > parseFloat($oldPrice))
					{
						this.refreshHistory($r);
						//$('#bidding_history table tr:first td').attr('style', 'text-decoration:line-through;')
					}
					return true;
//					// even / odd styling handler
//					if ($('#bidding_history table tr:first').attr('class') != 'gray')
//					{
//						$cssClass = 'gray';
//					}
//					else
//					{
//						$cssClass = '';
//					}
//
//					// remove no bids message
//					$('#bidding_history .nobids').remove();
//					$newRow = "<tr class=\"" + $cssClass + "\"><td>" + $response[$r].highest + "</td><td><strong>&euro; <strong><label><strong>" + $newPrice + "</strong></label></td></tr>";
//					$container.prepend($newRow);
//
//                    // part for multiitem auction line winner separator
//                    if ($('#countOfProducts').length == 1)
//                    {
//                        $('#lead-line').attr('id', '');
//                        $countOfProducts = parseInt($('#countOfProducts').text()) - 1;
//                        //$('#bidding_history table tr:eq(' + $countOfProducts + ')').attr('id', 'lead-line');
//                        $('#bidding_history table tr:eq(' + ($countOfProducts+1) + ') td').attr('class', 'blue');
//                    }
//
//                    // part for nice line in singleitem auction
//                    if ($('#countOfProducts').length == 0)
//                    {
//                        $('#win-line').attr('id', '');
//                        $('#bidding_history table tr:first').attr('id', 'win-line');
//                    }
				}

				// remove hipertrophy
				
//				if ($('#bidding_history table tr').length > $('#countHistoryRecords').html())
//				{
//					$('#bidding_history table tr:last').remove();
//				}
			}
		}
	};

	/*
	 * check is there any new auction in system
	 */
	this.lookupNewAuctions = function()
	{
		obj = this;

		$req = this.getActiveAuctions(true);

        $futures = this.getFutureAuctions();

		this.ajaxFlag = 0;

        if ($('#index-index').length > 0)
        {
            $firstpageParam = "&f=1";
        }
        else
        {
            $firstpageParam = "&f=0";
        }

        if ($('#product-category-id').length > 0)
        {
            $categoryParam = "&c="+$('#product-category-id').html();
        }
        else
        {
            $categoryParam = "&c=0";
        }
        
        
		// check for new auctions
		$.getJSON("/processor/get-new-auctions/", "a=" + $req + $firstpageParam + '&fu=' + $futures + $categoryParam, function(json)
		{
			// get response with new auctions
			$response = eval(json);

			// if there's proper answer
			if (6 != $response)
			{  
				// action for first page content
				if ($('#index-index').length > 0)
				{
					// get templates and insert auction
					for ($r in $response)
					{
						window.location.reload();
						return true;
						
//
//						
//						// if auction is special
//						if (1 == $response[$r].is_special)
//						{
//							(function($atrid){
//								$.ajax({
//									type: "POST",
//									url: "/auction/get-active-front-auction-special",
//									data: "id=" + $atrid,
//									success: function($msg)
//									{
//										$('#speciale_offer .advert').fadeOut(function()
//										{
//											$('#speciale_offer .block_header').remove();
//											$(this).remove();
//											$('#speciale_offer').prepend($msg);
//											bindClickForBid();
//                                            bindClickForMultiBid();
//                                            bindFutureClickForBid();
//
//                                            // and check if exist future auction with given id - if yes, simply wipe it
//                                            if ($('.future_' + $atrid).length > 0)
//                                            {
//                                                $('.future_' + $atrid).fadeOut(function() {$(this).remove(); });
//                                            }
//
//										});
//									}
//								});
//							 })($response[$r].id);
//						}
//						// if auction is standard
//						else
//						{
//							$('#noauctionmsg').remove();
//							(function($atrid){
//								$.ajax({
//									type: "POST",
//									url: "/auction/get-active-front-auction",
//									data: "id=" + $atrid,
//									success: function($msg)
//									{
//
//                                        // if there's other active auctions defined, put auction above its
//                                        if ($('.activeOfr').length > 0)
//                                        {
//                                            $($msg).insertBefore('.activeOfr:first');
//                                        }
//                                        // if there's no active auction, but theres future auctions, put auction below
//                                        else if ($('.futureOfr').length > 0)
//                                        {
//                                            $($msg).insertAfter('.futureOfr:last');
//                                        }
//                                        else
//                                        {
//                                            $($msg).insertAfter('#last_offers .block_header');
//                                        }
//
//                                        $('#' + $atrid).fadeIn(function()
//                                        {
//                                           // and check if exist future auction with given id - if yes, simply wipe it
//                                            if ($('.future_' + $atrid).length > 0 && $(this).hasClass('notFuture'))
//                                            {
//                                                //$('.future_' + $atrid).fadeOut(function() {$(this).remove(); });
//                                            }
//
//                                            bindClickForBid();
//                                            bindClickForMultiBid();
//                                            bindFutureClickForBid();
//
//                                        });
//
//                                        if ($('.notFuture').length > 3)
//                                        {
//                                            //$('.futureOfr').fadeOut(function() {$(this).remove(); });
//                                        }
//
//
//										//old ver of this version above --> $('#' + $atrid).fadeIn(function(){bindClickForBid(); bindClickForMultiBid(); });
//
//									}
//								});
//							 })($response[$r].id);
//						}
					}
					// obj.updateStatus(json);
				}

				// actions for list
				if ($('#auction-all').length > 0)
				{
					// get templates and insert auction
					for ($r in $response)
					{

						window.location.reload();
						return true;
						
//						// get auction
//						(function($atrid){
//							$.ajax({
//								type: "POST",
//								url: "/auction/get-active-auction-on-list",
//								data: "id=" + $atrid,
//								success: function($msg)
//								{
//									// if there's other active auctions defined, put auction above its
//									if ($('.activeOfr').length > 0)
//									{
//										$($msg).insertBefore('.activeOfr:first');
//									}
//									// if there's no active auction, but theres future auctions, put auction below its
//									else if ($('.futureOfr').length > 0)
//									{
//										$($msg).insertAfter('.futureOfr:last');
//									}
//									// in other case just put auction on top
//									else
//									{
//										$('#auction-all').prepend($msg);
//									}
//
//									$('#' + $atrid).fadeIn(function() 
//                                    {
//										// and check if exist future auction with given id - if yes, simply wipe it
//										if ($('.future_' + $atrid).length > 0)
//										{
//											$('.future_' + $atrid).fadeOut(function() {$(this).remove(); });
//										}
//									});
//
//									bindClickForBid();
//                                    bindClickForMultiBid();
//                                    bindFutureClickForBid();
//								}
//							});
//						 })($response[$r].id);
					}
				}

				// actions for single auction
				if ($('#auction-show').length > 0)
				{
					// get templates and insert auction
					for ($r in $response)
					{
						// perform action only for current auction
						if ($response[$r].id == $('.offer_bids').attr('id'))
						{
                            // just refresh page
                            window.location = '/auction/show/id/' + $('.offer_bids').attr('id');
							// get auction
                            /*
							(function($atrid){
								$.ajax({
									type: "POST",
									url: "/auction/get-active-single-auction",
									data: "id=" + $atrid,
									success: function($msg)
									{
										$('.offer_bids').attr('class', 'offer_bids activeOfr');
										$('.offer_bids').html($msg);

										bindClickForBid();
									}
								});
							 })($response[$r].id);
                            */
						}
					}
				}
			}
		});


	};

	/*
	 * make a bid
	 */
	this.bidMe = function($auctionId)
	{
		obj = this;

        $.getJSON("/processor/bid/", "a=" + $auctionId, function(json)
		{
			// update auctions status
			$response = eval(json);
			$('div.multiBidMe').bind('click');
			
			if ( !in_array($response, obj.errorStatuses) && !in_array($response['status'], obj.bidErrorStatuses)) 
			{
				obj.useCredits($response);

                if ($response['show_overbid'])
                {
                    $.showAkModal('/auction/activate-overbid-service/a/' + $auctionId,$dictionary.get('overbid_service'),300,150);
                }
                else
                {
                    showInfo($dictionary.get('thank_you_for_this_bid'));
                }


			}

            if (in_array($response['status'], obj.bidErrorStatuses))
            {
                obj.useCredits($response);
                obj.messenger($response['status']);
            }

            if ($response == 2)
            {
            	$.showAkModal('/auction/insufficent-credits-msg/a/' + $auctionId,$dictionary.get('insufficent_credits'),300,150);
            }
            else
            {
            	obj.updateStatus(json);
            }

		});
	};

	function showAutobidForm($message, $auctionId, $amount)
	{
		obj = this;
		if ($('.autobid-messenger').html() != "")
		{
			$('.autobid-messenger').remove();
		}
		
		$html = '<div class="autobid-messenger" style="display:none">'+
					'<div class="msg">'+
						$message + '<br /><br /><input type="test" class="onlyNumbers" id="maxAutobidValue" name="maxAutobidValue" value="'+$amount+'"/>'+
						'<div id="popup_panel">'+
							'<input id="popup_ok" type="button" value=" Ok " />'+
							'<input id="popup_cancel" type="button" value=" Cancel " />'+
						'</div>'+
					'</div>'+
				'</div>';
		

		$('#container').prepend($html);

		// user accept autobid
		$('#popup_ok').bind('click', function() {

			$.getJSON("/processor/set-autobid/", "a=" + $auctionId + "&v=" + $("#maxAutobidValue").attr('value'), function(json)
		    {
				$response = eval(json);

				if ($response['status'] == 33){
					$('.autobid-messenger').remove();
					showInfo( $dictionary.get('autobid_set_success') );
					obj.refreshHistory($auctionId);
					
		    	}
				
				if ($response['status'] == 13)
				{
					$increase_rate = $('#'+$auctionId+'_bid_price_increase_rate').html();
					showInfo( $dictionary.get('bid_to_small_increase_rate') + ' &euro; ' + $increase_rate);
					obj.refreshHistory($auctionId);
				}
				else
				{
		            if ( $response && in_array($response['status'], obj.bidErrorStatuses) )
		            {
		                obj.messenger($response['status']);
		                obj.refreshHistory($auctionId);
		            }
					
				}
				
		    });

			
		});
		
		$('#popup_cancel').bind('click', function() {
			$('.autobid-messenger').remove();
		});
		$(".onlyNumbers").keypress(function(event) {
			  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
			  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
			  if (!event.which ||
			      ((49 <= event.which && event.which <= 57) || event.which == 46 || event.which == 44) || // Always 1 through 9
			      (48 == event.which && $(this).attr("value")) || 
			      isControlKey) { 
			    return;
			  } else {
			    event.preventDefault();
			  }
		 });		
		
		$('.autobid-messenger').fadeIn();
		
		
		//setTimeout(function() { $('.messenger').fadeOut(function(){$(this).remove(); }); }, 2000);
	}

	this.multiBidMe = function($auctionId, $amount)
	{
		if(!$amount){
			showInfo($dictionary.get('bid_too_small'));
			return false;
		}
		
		// confirm bid message
		$message = $dictionary.get('confirm_bid_message');
		$message = $message.replace('[bidprice]', $amount);
		jConfirm($message, '', function(r) {
			if(r)
			{
				$bidder.multiBidMeOk($auctionId, $amount);
			}
		});
		
		/* Disabled autobid
		

		// confirm autobid message
		$autobidMessage = $dictionary.get('confirm_autobid_message');
		
		$.getJSON("/processor/check-autobid/", "a=" + $auctionId, function(jsonResult)
		{
			
			// jesli uzytkownik nie ma w tej chwili aktywnego autobida
			if(!jsonResult['result'])
			{

				jConfirm($autobidMessage, '', function(r) {
					
					if(r)
					{
						$increase_rate = $('#'+$auctionId+'_bid_price_increase_rate').html();
						$autobid_message = "<p style='margin:10px;'>Vul het maximale bedrag in dat u wilt bieden, dit bedrag geld als maximum dat u voor dit product wilt betalen. Zodra u bent overboden zal er automatisch een nieuw bod onder uw naam worden uitgebracht. Hierdoor hoeft u niet constant de veiling in de gaten te houden en handmatige bods plaatsen.<br><br>NB. Zodra u bent overboden zal uw bod met maximaal "+$increase_rate+" omhoog gaan. U ontvangt bericht zodra uw maximale autobid is overboden.</p>";
						showAutobidForm($autobid_message, $auctionId, $amount);
						
					}
					else
					{
						// confirm bid message
						$message = $dictionary.get('confirm_bid_message');
						$message = $message.replace('[bidprice]', $amount);
						jConfirm($message, '', function(r) {
							if(r)
							{
								$bidder.multiBidMeOk($auctionId, $amount);
							}
						});
					}
				
				});

			}
			// last 2 seconds, autobid is disabled
			else if(jsonResult['result'] == 2)
			{
				// confirm bid message
				$message = $dictionary.get('confirm_bid_message');
				$message = $message.replace('[bidprice]', $amount);
				jConfirm($message, '', function(r) {
					if(r)
					{
						$bidder.multiBidMeOk($auctionId, $amount);
					}
				});
				
			}
			else
			{
				// confirm bid message
				$message = 'Your autobid value is &euro;'+jsonResult['value'];
				//$message = $message.replace('[bidprice]', $amount);
				showInfo($message);
				
			}
				
			
			
		});
		
		*/
		
		
	}
	
	
	/*
	 * make a multi bid
	 */
	this.multiBidMeOk = function($auctionId, $amount)
	{
	    obj = this;
		$.getJSON("/processor/bid/", "a=" + $auctionId + '&m=' + $amount, function(json)
		{
			// update auctions status
			$response = eval(json);
			
			if ( !$response || (!in_array($response, obj.errorStatuses) && !in_array($response['status'], obj.bidErrorStatuses)) )
			{
				//obj.useCredits($response);

                if ($response && $response['show_overbid'])
                {
                    $.showAkModal('/auction/activate-overbid-service/a/' + $auctionId,$dictionary.get('overbid_service'),300,150);
                }
                else
                {
                    showInfo($dictionary.get('thank_you_for_this_bid'));
                    obj.refreshHistory($auctionId);
                    
                    $.ajax({url:'/index/analytics/bid_ok?auctionId=' + $auctionId + '&amount=' + $amount});
                    if( $('#isHomePage').length > 0 )
                    {

                    	function moveMe($auctionId)
                    	{
                        	window.location = "/auction/show/id/"+$auctionId;
                    	}
                    	moveMe($auctionId);                  	
                    	
                    }
                    

                }
			}

			if ($response && $response['status'] == 13)
			{
				$increase_rate = $('#'+$auctionId+'_bid_price_increase_rate').html();
				showInfo( $dictionary.get('bid_to_small_increase_rate') + ' &euro; ' + $increase_rate);
			}
			else
			{
	            if ( $response && in_array($response['status'], obj.bidErrorStatuses) )
	            {
	                //obj.useCredits($response);
	                obj.messenger($response['status']);
	            }
				
			}

            if ($response == 2)
            {
            	$.showAkModal('/auction/insufficent-credits-msg/a/' + $auctionId,$dictionary.get('insufficent_credits'),300,150);
            }
            else
            {
            	obj.updateStatus(json);
            }

		});

	};

    this.showOverbidQuestion = function($auctionId)
    {

    }

    /*
     * take user credits in visual way
     */
    this.useCredits = function($response)
    {
        $('#user-credits').html($response['user_credits']);

        // just color efects
        $('#user-credits').css('color', '#FF8B1F');
        setTimeout("$('#user-credits').css('color', '#868686');", 2000);
    }

    /*
     * show some message
     */
	this.messenger = function($response)
	{
		if ($response === 0)
		{
			showInfo($dictionary.get('error_during_bidding'));
		}
		else if ($response == 2)
		{
			// showInfo($dictionary.get('insufficent_credits'));
		}
		else if ($response == -1)
		{
			// showInfo($dictionary.get('general_update_error'));
		}
		else if ($response == -2)
		{
			// showInfo($dictionary.get('general_update_error'));
		}
		else if ($response == 3)
		{
			showInfo($dictionary.get('you_already_lead_in_this_auction'));
		}
		else if ($response == 7)
		{
			showInfo($dictionary.get('fill_empty_fields'));
		}
        else if ($response == 9)
		{
			showInfo($dictionary.get('bid_too_small'));
		}
        else if ($response == 10)
		{
			showInfo($dictionary.get('user_bids_exhaused_for_this_auction'));
		}
        else if ($response == 11)
		{
			showInfo($dictionary.get('auctions_bids_exhaused_for_this_auction'));
		}
        else if ($response == 12)
		{
			showInfo($dictionary.get('bid_to_large'));
		}
        else if ($response == 13)
		{
			showInfo($dictionary.get('bid_to_small_increase_rate'));
		}
        else if ($response == 15)
		{
			showInfo($dictionary.get('you_already_set_autobid_value'));
		}
        else if ($response == 16)
		{
			showInfo($dictionary.get('you_have_no_paid_auctions'));
		}
		
	};
};

$(document).ready(function() {

    $('input').blur(function()
    {
        $('input').removeClass("focus");
    })
    .focus(function() {
        $(this).addClass("focus")
    });


	$bidder = new Bidder();

	// magically check status
	setInterval("$bidder.checkStatus();", "1000");

	// and put new auctions
	setInterval("$bidder.lookupNewAuctions();", "10000");

    // make a bid
	bindClickForBid();
    bindClickForMultiBid();
    bindFutureClickForBid();
});

