/**
 * Variáveis globais
 */
var che = 1;
var showUser_history = 0; /////////// histórico de ofertas no detalhamento do produto
var montharray = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var running = [];
var refreshID_1;
var refreshID_2;
var Timer = 0;
var quitting;
var minTimeoutRequest = 1;
var maxTimeoutRequest = 3;
var getUpdateData = false;
var getCurrentData = false;
var showHistoryOnUpdate = false;

function is_array(obj)
{
	return (obj.constructor.toString().indexOf("Array") != -1);
}

function getCounterByTime(diff, unit)
{
	var days = 0;
	var hours = 0;
	var minutes = 0;
	var seconds = 0;
	var rest;
	var diff;
	var rest1;
	var rest2;
	var partialDays;
	var partialHours;
	var partialMinutes;
	var difference;

	if (diff % 86400 <= 0)  // there are 86,400 seconds in a day
	{
		days = diff / 86400;
	}

	if(diff % 86400 > 0)
	{
		rest = (diff % 86400);
		days = (diff - rest) / 86400;

		if( rest % 3600 > 0 )
		{
			rest1 = (rest % 3600);
			hours = (rest - rest1) / 3600;

			if( rest1 % 60 > 0 )
			{
				rest2 = (rest1 % 60);
				minutes = (rest1 - rest2) / 60;
				seconds = rest2;
			}
			else
			{
				minutes = rest1 / 60;
			}
		}
		else
		{
			hours = rest / 3600;
		}
	}

	switch(unit)
	{
		case 'd':
		case 'D':

			partialDays = 0;

			partialDays += (seconds / 86400);
			partialDays += (minutes / 1440);
			partialDays += (hours / 24);

			difference = days + partialDays;

		break;

		case 'h':
		case 'H':

			partialHours = 0;

			partialHours += (seconds / 3600);
			partialHours += (minutes / 60);

			difference = hours + (days * 24) + partialHours;

		break;

		case 'm':
		case 'M':

			partialMinutes = 0;

			partialMinutes += (seconds / 60);

			difference = minutes + (days * 1440) + (hours * 60) + partialMinutes;

		break;

		case 's':
		case 'S':

			difference = seconds + (days * 86400) + (hours * 3600) + (minutes * 60);

		break;

		case 'a':
		case 'A':

			difference = {
				"days" : days,
				"hours" : hours,
				"minutes" : minutes,
				"seconds" : seconds
			};

		break;
	}
	
	if (difference && unit != 'A' && unit != 'a')
	{
		/*
		difference['hours'] = str_pad(difference['hours'], 2, '00', STR_PAD_LEFT);
		difference['minutes'] = str_pad(difference['minutes'], 2, '00', STR_PAD_LEFT);
		difference['seconds'] = str_pad(difference['seconds'], 2, '00', STR_PAD_LEFT);
		*/

		if (difference['days'] > 1)
		{
			return difference['days'] + ' dias + ' + difference['hours'] + ':' + difference['minutes'] + ':' + difference['seconds'];
		}
		else if (difference['days'] == 1)
		{
			return difference['days'] + ' dia + ' + difference['hours'] + ':' + difference['minutes'] + ':' + difference['seconds'];
		}

		return difference['hours'] + ':' + difference['minutes'] + ':' + difference['seconds'];
	}

	return difference;
}

function randomParamForNoCache()
{
	var date = new Date();
	return date.getTime();
}

function randomNumber(from, to)
{
	return Math.floor(from + Math.random()*to);
}

/**
 * Encontra determinado elemento
 * @param n
 * @param d
 * @returns
 */
function MM_findObj(n, d)
{
    //v4.01
    var p, i, x;

    if (!d)
    {
        d = document;
    }

    if ((p = n.indexOf("?")) > 0 && parent.frames.length)
    {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }

    if (!(x = d[n]) && d.all)
    {
        x = d.all[n];
    }

    for (i = 0; !x && i < d.forms.length; i++)
    {
        x = d.forms[i][n];
    }
    for (i = 0; !x && d.layers && i < d.layers.length; i++)
    {
        x = MM_findObj(n, d.layers[i].document);
    }

    if (!x && d.getElementById)
    {
        x = d.getElementById(n);
    }
    return x;
}

/**
 * Realiza a troca de imagens
 */
function MM_swapImage()
{
    //v3.0
    var i;
    var j = 0;
    var x;
    var a = arguments;

    document.MM_sr = [];

    for (i = 0; i < (a.length - 2); i += 3)
    {
        if ((x = MM_findObj(a[i])) != null)
        {
            document.MM_sr[j++] = x;

            if (!x.oSrc)
            {
                x.oSrc = x.src;
                x.src = a[i + 2];
            }
        }
    }
}

/**
 * Realiza a restauração da imagem anterior, associada a troca de imagem
 */
function MM_swapImgRestore()
{
    //v3.0
    var i;
    var x;
    var a = document.MM_sr;

    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
    {
        x.src = x.oSrc;
    }
}

/**
 * Faz um elemento piscar
 * @param countt
 */
function blinkIt(countt)
{
    var s = document.getElementById("Amt" + countt);
	if (s != null)
    {
        if (che % 2 == 0)
        {
            s.style.visibility = "hidden";
        }
        else
        {
            s.style.visibility = "visible";
        }
        che = che + 1;
    }

    setTimeout("blinkIt(" + countt + ")", 500);
}

/**
 * Limpa um array removendo elementos que não correspondem ao elemento passado
 * @param actual
 * @returns {Array}
 */
function cleanArray(actual, element)
{
	var newArray = [];

	for (var i = 0; i < actual.length - 1; i++)
	{
		if (actual[i] != element)
		{
			newArray.push(actual[i]);
		}
	}

	return newArray;
}

/**
 * Cria o html do historico de BIDs baseado nos dados passados por parametros
 * @param data
 * @returns {String}
 */
function createHistoryHtml(data)
{
	// criando o header do html
	var html1 = "";
	html1 += "<table style='font-size:11px; font-family:Aria, Verdana;' cellpadding='0' cellspacing='0' width='187px'>";
	html1 += "    <tr>";
	html1 += "        <td style='background-color:#DEDEDE; color:#000;' align=center height=20px width=40%>Ofertas</td>";
	html1 += "		  <td style='background-color:#DEDEDE; color:#000;' align=center width=35%>Usu&aacute;rio</td>";
	html1 += "		  <td style='background-color:#DEDEDE; color:#000;' align=center width=25%>Tipo</td>";
	html1 += "	  </tr>";

	// criando as linhas com os dados
	//var dataArr = cleanArray(data.split('|'), '');
	var dataArr = data.split('||');
	var infoArr; 
	var html2 = "";
	var dataLength = dataArr.length;
	
	//$('#monitor').html(data);
	
	// faz um loop em todos os elementos
	for (var x = 0; x < dataLength; x++)
	{
		infoArr	= dataArr[x].split(":");
		if(infoArr[1]!="" && infoArr[1]!= undefined){
			html2 += "<tr>";
			html2 += "    <td align='center' width='20%' height='17' style='border-bottom:#ccc solid 1px;'>" + infoArr[0] + "</td>";
			html2 += "    <td align='center' width='40%' style='border-bottom:#ccc solid 1px;'>" + left(infoArr[1],10) + "</td>";
			html2 += "    <td align='center' width='40%' style='border-bottom:#ccc solid 1px;'>" + infoArr[2] + "</td>";
			html2 += "</tr>";
		}
	}

	// criando html final
	var html3 = "";
	html3 = "</table>";

	return html1 + html2 + html3;

}

/**
 * Obtém a tabela de BIDs realizados para um determinado produto
 * @param idname
 * @param showUser_history
 * @param set_autoferta
 */
function GetBidTable(idname, showUser_history, set_autoferta)
{
	
	
	
	if (set_autoferta == null || set_autoferta == ""){
		set_autoferta = 0;
	}

	if (showUser_history == null || showUser_history == ""){
		showUser_history = 0;	
	}

	
	if (getUpdateData == true)
	{
		return;
	}
	else
	{
		getUpdateData = true;
	}
			
	$.ajax({
        type: "GET",
        url: "get_update.php",
        dataType: "html",
		data: {id: + idname, user_history: + showUser_history, set_autoferta: + set_autoferta, rnd: randomParamForNoCache(), show_history: (showHistoryOnUpdate == true ? 1 : 0)},
        success: function (data)
        {
			updates = data.split("##");
			
			//$('#monitor').html(idname + " " + showUser_history + "  " + set_autoferta);
			
			$('#Amt' + idname).html(updates[0]); //valor atual do lance
        	$('#SAmt' + idname).html(updates[1]);		//valor atual do lance	
        	$('#Sav' + idname).html(updates[2]);		//valor economizado 
        	$('#Usr' + idname).html(updates[3]);		//login do ultimo bider
			
			$('#futu' + idname).html(updates[4]);		//timestamp
        	$('#totb' + idname).html(updates[5]);		//valor sem a virgula	
			
			
        	$('#His' + idname).html(createHistoryHtml(updates[6])); // historico

			if (set_autoferta == 1 || set_autoferta == '1' || set_autoferta != '0' )
        	{
				$('#oferta' + idname).html(updates[7]);		// autooferta
        	}
        	$('#bidcost' + idname).html(updates[8]);		//valor do bid 
        	$('#desc' + idname).html(updates[9]);			//numero de lances dados nesse produto / desconto para comprar esse produto
        	$('#fprice' + idname).html(updates[10]);		//valor do frete
        	$('#desc_value' + idname).html(updates[11]);	//valor com desconto
        	$('#desc_final' + idname).html(updates[12]);	//desconto percentual ao valor do produto final	
			
			getUpdateData = false;
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
        	// tratar erro
			getUpdateData = false;
        }
    });
}

/**
 * Exibe tabela de BIDs para um determinado produto, podendo exibir somente o histórico de um determinado usuário
 * @param idname
 * @param user_history
 * @param light
 */
function GetBid(idname, user_history, light)
{
    var updates;
    var set_autoferta = $('#set_autoferta' + idname).text();	
	showUser_history = user_history;
	
	if(showUser_history==null || showUser_history==""){
		showUser_history = 0;	
	}

	if(set_autoferta==null || set_autoferta==""){
		set_autoferta = 0;	
	}
	
//
    if (showUser_history == 0)
    {
//        $('#hist_oferta1').css(
//        {
//            'background-image': 'url(' + TFOLD + '/img_files/hist_oferta_red_off.gif)',
//            'font-weight': 'bold'
//        });
//        $('#hist_oferta2').css(
//        {
//            'background-image': 'url(' + TFOLD + '/img_files/hist_oferta_right_red_on.gif)',
//            'font-weight': 'normal'
//        });
    }
    else
    {
//        $('#hist_oferta1').css(
//        {
//            'background-image': 'url(' + TFOLD + '/img_files/hist_oferta_red_on.gif)',
//            'font-weight': 'normal'
//        });
//        $('#hist_oferta2').css(
//        {
//            'background-image': 'url(' + TFOLD + '/img_files/hist_oferta_right_red_off.gif)',
//            'font-weight': 'bold'
//        });
    }
	
	//alert(showUser_history + "  " + set_autoferta);
    GetBidTable(idname, showUser_history, set_autoferta);

    if (light == 1)
    {
        $('#Amt' + idname).effect("highlight", {}, 1000);
    }
}

/**
 * Gera a auto-oferta efetivamente
 * @param strmin
 * @param strmax
 * @param strno
 * @param autop
 */
function storeauto(strmin, strmax, strno, autop)
{

	 //alert(strmin + "  : " +  strmax +  " :  " +  strno + "  : " +  autop);
	

    $.get("store_auto.php", {
        minb: +strmin,
        maxb: +strmax,
        nob: +strno,
        pid: +autop
    }, function (data)
    {
		//if(data!="" && data!=null){	
		//	alert(data);	
		//}
			
        if (data == '0')
        {
            alert("Ofertas insuficientes");
        }
        else if (data == 'login#1#')
        {
            alert("Efetue login para poder configurar o auto lance.");
        }
        else if (data == '-8')
        {
            alert("Efetue login para poder configurar o auto lance.");
        }
		else if (data == '-1')
        {
            alert("Você comprou este produto no 'compre agora' e não pode mais particiar desta venda.");
        }
        else if (data == '-2')
        {
            alert("Auto oferta não permitido para este produto");
        }
        else if (data == '-3')
        {
            alert("Este produto está disponível apenas para iniciantes.");
        }
        else if (data == '-4')
        {
            alert("Você atingiu o limite máximo de produtos ganhos no período, para mais detalhes consulte os Termos de Uso.");
        }
        else if (data == '-9')
        {
            alert("O tempo para dar lances já foi encerrado.");
        }		
        else
        {
            showauto(autop);
            alert("Auto oferta configurado");
        }
    });
}

/**
 * Realiza a configuração da auto-oferta
 * @param autop
 */
function setauto(autop)
{
    var strmin = document.getElementById("minbid").value;
	var strmax = document.getElementById("maxbid").value;
	var strno = document.getElementById("bidno").value;

    strmin = strmin.replace(".", "");
    strmin = strmin.replace(",", ".");

    strmax = strmax.replace(".", ",");
    strmax = strmax.replace(",", ".");

    if (strno == "" || strmax == "" || strmin == "")
    {
        alert("Campos vazios");
    }
    else
    {
        if (strno != parseInt(strno))
        {
            alert("Número de ofertas inválido");
        }
        else if (isNaN(strno) || isNaN(strmax) || isNaN(strmin))
        {
            alert("Somente números");
        }
        else
        {
            if (parseFloat(strmin) >= parseFloat(strmax))
            {
                alert("A oferta máxima deve ser maior que a mínima!");
                document.autobid.minbid.value = "";
                document.autobid.maxbid.value = "";
                document.autobid.bidno.value = "";
            }
            else if (parseInt(strno) > 100)
            {
                alert("Você pode configurar no máximo 100 ofertas para o auto oferta.");
            }
            else
            {
                $('#set_autoferta' + autop).html("1");
                storeauto(strmin, strmax, strno, autop);
            }
        }
    }
}

/**
 * Exibe a auto-oferta
 * @param autop
 */
function showauto(autop)
{
    $.get("show_auto.php", {
        prid: +autop
    }, function (data)
    {
		//alert(data);	
        $('#Auto' + autop).html(data);
		//alert($('#Auto' + autop).html());
    });
}

/**
 * Remove o timer de auto-oferta
 * @param autop
 * @param autoid
 * @param rfrsh
 */
function unsetauto(autop, autoid, rfrsh)
{		

	//alert(autop + "  " + autoid + "   "  + rfrsh);


    $.get("unset_auto.php", {
        aid: +autoid,
		pid: +autop
    }, function (data)
    {
        $('#Auto' + autop).html(data);
        $('#set_autoferta' + autop).html("0");
        if (rfrsh == "1")
        {
            window.location.reload();
        }
    });
}

/**
 * Obtém as informações dos leilões passados via PIPE na requisição
 * @param auctionid
 */
function GetUpdate(auctionid)
{
	var gauctions;
	var gdivis;

	var ids = auctionid.split('|');

	for (var x = 0; x < ids.length - 1; x++)
	{
		if ($('#totb' + ids[x]).length <= 0)
		{
			return;
		}
	}
	
	ServerMonitor.reset();

	$.ajax({
        type: "GET",
        url: "get_ex_date.php",
        timeout: 2000,
        dataType: "html",
        data: {id: auctionid, rnd: randomParamForNoCache()},
        success: function (data)
        {
			
			ServerMonitor.update(false);
			
			gauctions = data.split("||");
							   
            for (m = 0; m <= gauctions.length - 1; m++)
            {
            	if (gauctions[m] != undefined)
            	{
	                gdivis = gauctions[m].split("##");
					
	                gdivis[1] = (gdivis[1]);
	                gdivis[0] = parseFloat(gdivis[0]);
	                gdivis[3] = parseFloat(gdivis[3]);
					
	                $('#pause' + gdivis[0]).html(gdivis[2]);						

	                if ($('#totb' + gdivis[0]).length > 0)
					{
						//if(m==0){
						//	$('#monitor').html($('#totb' + gdivis[0]).text() + " | " + gdivis[1] + " | " + gauctions[m] + " | " + showUser_history);
						//}
						
						var gtotb = $('#totb' + gdivis[0]).text();
						gtotb = parseFloat(gtotb);
						
						$('#quitting_status' + gdivis[0]).html(gdivis[3]);
						$('#quitting_status' + gdivis[0]).html('0');

						if(gdivis[1] != gtotb)
						{
							//$('#monitor').html(showUser_history);
							GetBid(gdivis[0], showUser_history, 1);
						}
					}
            	}
            }
			
			refreshID_1 = setTimeout("GetUpdate('"+auctionid+"')", 1000);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
        	ServerMonitor.update(true);

			var number = randomNumber(minTimeoutRequest, maxTimeoutRequest) * 1000;
			
			refreshID_1 = setTimeout("GetUpdate('"+auctionid+"')", number);
        }
    });
}

/**
 * Obtém o status atual dos leilões passados via PIPE na requisição
 * @param auctionid
 */
function GetCurrent(auctionid)
{
	if (getCurrentData == true)
	{
		return;
	}
	else
	{
		getCurrentData = true;
	}
	
	var gauctions;
	var gdivis;

	$.ajax({
        type: "GET",
        url: "get_current.php",
        timeout: 2000,
        dataType: "html",
        data: {id:auctionid, rnd: randomParamForNoCache()},
        success: function(data)
        {
			
        	gauctions=data.split("||");
			
			//$('#monitor').html(data);
			
			for(n=0;n<=gauctions.length - 1;n++)
			{
				if(gauctions[n] != undefined)
				{
					gdivis=gauctions[n].split("##");
					gdivis[0] = $.trim(gdivis[0]);
					if(gdivis[2] != null)
					{
						$('#status'+gdivis[0]).html(gdivis[2]);
						$('#futu'+gdivis[0]).html('0');
					}
					else
					{
						$('#status'+gdivis[0]).html('');
						$('#futu'+gdivis[0]).html(gdivis[1]);
					}

					if(gdivis[3] != null)
					{
						$('#us_id'+gdivis[0]).html(gdivis[3]);
			        }
				}
			}

			getCurrentData = false;
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
        	// tratar erro
			getCurrentData = false;

			if (textStatus == 'timeout')
			{
				setTimeout("GetCurrent('"+auctionid+"')", 1000);
			}
        }
    });
}

/**
 * Realiza BID em um produto
 * @param idname
 * @param biduser
 */
function bidnow(idname, biduser)
{
	if(parseInt(idname)==0 || parseInt(biduser)==0){
		alert("Faça seu login para participar e dar lances!");
		return;	
	}
		
	$.ajax({
        type: "GET",
        url: "bid_now.php",
		dataType: "html",
        data: {id:+ idname, user: biduser, rnd: randomParamForNoCache()},
        success: function(data)
        {
	        var data_array = data.split("#");
	        if (data_array[0] == "Insufficient Balance")
	        {
	            var buy_bid = confirm("Seus lances terminaram. Você gostaria de adquirir mais lances?");
	            if (buy_bid)
	            {
	                window.location = "mc_comprar_bid.php?type=buybid";
	            }
	        }
	        else if (data_array[0] == "No bid")
	        {
	            var normal = 1;
	            var autobid = 2;
	            var sms = 4;
	            var voice = 8;
	            var tv = 16;
	            var beginner = 32;
	            var type_oferta = data_array[1];

	            alert("Ofertas válidas somente para " + type_oferta);

	        }
	        else if (data_array[0] == "expired")
	        {
	            alert("Ofertas encerradas, aguarde a verificação do ganhador");
	        }
	        else if (data_array[0] == "login")
	        {
	            alert("Faça seu login para participar e dar lances");
	        }			
	        else if (data_array[0] == "Bought")
	        {
	            alert("Você comprou este produto utilizando o 'Compre Agora'");
	        }
	        else if (data_array[0] == "Blocked")
	        {
	            alert("Sua conta está bloqueada pelo administrador do sistema");
	        }			
	        else
	        {
	            var periodo = data_array[0].split(":");
	            if (periodo[0] == "LimiteExcedido")
	            {
	                alert("Você atingiu o limite máximo de compras no periodo de " + periodo[1] + " dias, para mais detalhes consulte os Termos de Uso");
	            }
				GetBidNum();
	        }
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
        	// tratar erro
        }
    });
}

/**
 * Obtém a quantidade de BIDs disponíveis para o usuário logado
 */
function GetBidNum()
{
	$.ajax({
        type: "POST",
        url: "get_bidnum.php",
        dataType: "html",
		timeout: 3000,
        data: {rnd: randomParamForNoCache()},
        success: function(data)
        {
        	$('#bid_num').html(data);
			$('#bid_count').html(data);
        	//setTimeout("GetBidNum()",3000);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
        	if (textStatus == 'timeout')
			{
				setTimeout("GetBidNum()",1000);
			}
			else
			{
				//setTimeout("GetBidNum()",3000);
			}
        }
    });
}




/**
 * Realiza a atualização dos contadores e as informações dos leilões
 * @param auctionid
 * @param generation
 */
function tryToCountdown(auctionid, generation){
	var auctions;
	var divs;

	if (generation != UpdateGeneration)
	{
		return;
	}
		
	auctions = auctionid.split("|");

	for (n = 0; n <= auctions.length - 1; n++)
	{
	    if (auctions[n] != undefined && auctions[n] != '')
	    {
	        quitting = $('#quitting_status' + auctions[n]).text();
	    }
	}

	Timer = Timer + 1;

	if ((Timer % 10 == "0") || (Timer == "1") || quitting == 1)
	{
	    GetCurrent(auctionid);
		GetBidNum();
	}
	
	var cauctionid = "auctionid";
	var tauctions = auctionid.split("|");


	for (i = 0; i <= tauctions.length - 1; i++)
	{
			
	    if (tauctions[i] != undefined && tauctions[i] != "")
	    {	
			
	        var dd = $('#futu' + tauctions[i]).text();
	        var status = $('#status' + tauctions[i]).text();
	        var paus = $('#pause' + tauctions[i]).text();
	        var us_id = $('#us_id' + tauctions[i]).text();

			var current_user_id = $('#current_user_id').html();
			var user_id = '';

			if (us_id != '')
			{
				var temp_user_data = us_id.split('|');
				us_id   = temp_user_data[0];
				user_id = temp_user_data[1];
			}
			
	        if (status == "closed")
	        {
				
	            GetBid(tauctions[i], showUser_history, 0);
				
	            //Sumir com o div do relógio
	            $('#Bid' + tauctions[i]).hide();
	            $('#End' + tauctions[i]).hide();
				$('#bt-verificando' + tauctions[i]).hide();

				$('#bt-on' + tauctions[i]).hide();
	            $('#bt-off' + tauctions[i]).show();

	            if (us_id == "winner" && user_id == current_user_id && current_user_id != 0)
	            {
	            	$('#end_msg1' + tauctions[i]).show();
	            }
	            else
	            {
	                $('#end_msg2' + tauctions[i]).show();
	            }

	            //remover o ID corrente divis[0] da variavel auctionid
	            auctionid = "";
				
	            for (z = 0; z <= tauctions.length - 1; z++)
	            {
	                if ((z != i) && (tauctions[z] != "removed"))
	                {
	                    auctionid = auctionid + tauctions[z];
	                    if (z < tauctions.length - 1)
	                    {
	                        auctionid = auctionid + "|";
	                    }
	                }
	                else
	                {
	                    tauctions[z] = "removed";
	                }
	            }
				
	        }
	        else if (status == "closing")
	        {
	            //Escrever no div do relógio, aguardando vencedor
	            $('#bt-on' + tauctions[i]).hide();
	            $('#bt-off' + tauctions[i]).hide();
				$('#bt-verificando' + tauctions[i]).show();

				valll = "<span class=\"timer_countdown\">00:00:00</span>";
				$('#Bid' + tauctions[i]).html(valll);
				$('#Bid' + tauctions[i]).show();
	        }
	        else
	        {
				
				 //alert($('#Bid' + tauctions[i]).color);
					            
				$('#End' + tauctions[i]).hide();
	            $('#Bid' + tauctions[i]).show();

				$('#bt-on' + tauctions[i]).show(); 
	            $('#bt-off' + tauctions[i]).hide();
				$('#bt-verificando' + tauctions[i]).hide();

				var cdd = dd - 1;
	            var valll;

	            if (cdd < 0)
	            {
	            	dd = cdd = 0;
	            }
				
	            $('#futu' + tauctions[i]).html(cdd);
				dd = dd * 1000;
				
				var dateData = getCounterByTime(cdd, 'a');
				dday  = dateData['days'];
				dhour = dateData['hours'];
	            dmin  = dateData['minutes'];
	            dsec  = dateData['seconds'];

	            if (dhour <= 9)
	            {
	                dhour = "0" + dhour;
	            }
	            if (dmin <= 9)
	            {
	                dmin = "0" + dmin;
	            }
	            if (dsec <= 9)
	            {
	                dsec = "0" + dsec;				
	            }
	            if (dd >= 1000)
	            {
	                if (dday > 0)
	                {
	                	valll = "<font size=\"1px\">" + dday + " dia" + (dday == 1 ? "" : "s") + " + </font>" + dhour + ":" + dmin + ":" + dsec;
	                }
	                else
	                {
	                	valll = dhour + ":" + dmin + ":" + dsec;
	                }
	            }

	            if (paus == 'yes')
	            {
	                valll = "Paused";
	            }
				else if (dd <= 10000)
	            {
	                valll = "<span class=\"timer_countdown\">" + dhour + ":" + dmin + ":" + dsec + "</span>";
	            }

				if (dd < 1000)
	            {
	                valll = "<span class=\"timer_countdown\">00:00:00</span>";
					$('#bt-on' + tauctions[i]).hide(); 
					$('#bt-off' + tauctions[i]).hide(); 
					$('#bt-verificando' + tauctions[i]).show();
	            }


				if (parseInt(dhour) < 1 && dday == 0)
	            {
					$('#inicio' + tauctions[i]).hide(); // layer de aviso
	            }

	            $('#Bid' + tauctions[i]).html(valll);
				$('#Bid' + tauctions[i]).show();
	        }
	    }

	}
	
	refreshID_2 = setTimeout("tryToCountdown('" + auctionid + "'," + generation + ")", 1000);

}


/**
 * Chama a função que realiza a atualização dos contadores e as informações dos leilões
 * @param auctionid
 */
function countdown(auctionid)
{
    UpdateGeneration = 0;	
	tryToCountdown(auctionid, UpdateGeneration);
}
