﻿var leilao = new leilaoUtil();
//var derby= new derbyUtil();

function leilaoUtil() {
    this.urlLeilao = '/paginasdirectas/leiloes/getLeilao.ashx';
	this.urlLeiloes = '/paginasdirectas/leiloes/getLeiloes.ashx';
	this.timer=1000;
	this.working=false;
	this.N=0;//nº pedidos
	this.dadosAnteriores=[];
	this.dadosActuais=[];
	this.iniLeiloes= [];//o primeiro
	this.iniIdLeilao= -1;// -1 não faz nada, >0 se página leilão
	this.iniNickName='0';
	this.iniIDUtilizador=0;
	this.outpuButLicitarID='butLicitar';
	this.outputSelValoresID='selValores';
	this.outputLicitacoesHistorico='licitacoes';
	this.settingLeilõesOn=1;
	this.settingLeilõesMostrarValores=1;

}

leilaoUtil.prototype.setIniUtilizador = function(id,nickname){
	this.iniIDUtilizador= id;
	this.iniNickName=nickname;
};

leilaoUtil.prototype.setIniLeiloes = function(idLeilao,idLeiloes){
	this.iniIdLeilao=idLeilao;
	this.iniLeiloes= idLeiloes;
};

leilaoUtil.prototype.getTempoFormatado = function(T){ 
var min = Math.floor(T/60);
var sec = T % 60;
var t = two	(sec);
var hr = Math.floor(min/60);
min = min % 60;
t = two(min) + "m:" + t;
var day = Math.floor(hr/24);
hr = hr % 24;
t = two(hr) + "h:" + t;
if (day > 0) {
	t = day + "d:" + t;
};
return t;
}

function two(x) {return ((x>9)?"":"0")+x}
function three(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}

//só chama os leilões activos.
leilaoUtil.prototype.getURLLeiloes = function () {
    var n = 0
    var url = '';
    var dados = [];
    if (this.iniIdLeilao > 0) {
        url = this.urlLeilao;
        if (this.N > 0) { dados = this.dadosActuais.LL; }
    } else {
        url = this.urlLeiloes;
        if (this.N > 0) {
            dados = this.dadosActuais;
        }
    };
    if (this.N == 0) {
        n = this.iniLeiloes.length;
    }
    else {
        n = dados.length;
    }
    for (i = 0, s = ""; i < n; i++) {
        if (this.N == 0) {
            s += ((i < (n - 1)) ? this.iniLeiloes[i] + "," : this.iniLeiloes[i]);
        } else {
            if (dados[i].E == 2) {
                s += ((i < (n - 1)) ? dados[i].L + "," : dados[i].L);
            };
        }
    };
    if (s.length == 0) return "";
    var d = new Date();
    return url + "?id=" + s + "&cache=" + d.getTime().toString();
}

leilaoUtil.prototype.ValorLicitacaoAlterado = function(idleilao, valor){
	if (this.N == 0)return false;
	if (this.dadosAnteriores.length == 0) return false;
	var v = [];
	if (this.iniIdLeilao > 0) {
		v = this.dadosAnteriores.LL;
	}
	else {
		v = this.dadosAnteriores;
	};
	
	for (i = 0; i < v.length; i++) {
		if (v[i].L == idleilao) {
			if (valor == v[i].V) {
				return false;
			}
			return true;
		}
	};
	return false
}

leilaoUtil.prototype.setEfeitoValorAlterado=function(idleilao){
	$("#leilaoV-" + idleilao).css({'border': '1px solid red'})
	setTimeout(function() {$("#leilaoV-" + idleilao).css({'border': '0px solid red'})}, 1000);
} 	

leilaoUtil.prototype.desenharLeiloes = function(){
	var id="";
	var v=[];
	if( this.iniIdLeilao>0 ){ v=this.dadosActuais.LL;}else {v=this.dadosActuais;};
	var d;
	
	for (i = 0; i < v.length; i++) {
		d = v[i];
		id = d.L.toString();
		if (d.E == 2) {
			$("#leilaoT-" + id).html(this.getTempoFormatado(d.T));
		}
		else {
			$("#leilaoT-" + id).html("Terminado");
			if(this.iniIdLeilao >0 && this.iniIdLeilao==d.L){
				 $("#butLicitar").hide("slow");
				 $("#selValores").hide("slow");
			}
		};
		if(this.settingLeilõesMostrarValores){
			$("#leilaoN-" + id).html("<img src='/userfiles/image/icons/nick.png' title='Actual licitador' /> Nick: " + d.N);
		}
		
		
		if (this.settingLeilõesMostrarValores){
		   		$("#leilaoV-" + id).html(this.getValorFormatado(d.V)); 
			} else {
				$("#leilaoV-" + id).html("<span style='font-size:12px'> Encerrado</span>");
		};
		
		if(this.ValorLicitacaoAlterado(d.L,d.V)){
			this.setEfeitoValorAlterado(d.L)
		};
	};

	if(this.leilaoDadosAlterados()) {
		this.desenharValores();
		this.desenharLicitacoes();
	}	
		
	this.dadosAnteriores=this.dadosActuais;
	this.N+=1;
	
};

//apenas diz respeito ao leilão
leilaoUtil.prototype.leilaoDadosAlterados = function () {
    if (this.iniIdLeilao == 0) return false;
    if (this.dadosActuais.length == 0) return false;
    if (this.dadosActuais.LL.length == 0) return false;
    if (this.dadosActuais.LL[0].L != this.iniIdLeilao) return false;
    if (this.N == 0) return true;
    if (this.dadosAnteriores.LL.length == 0) return true;
    if (this.dadosActuais.LL[0].V == this.dadosAnteriores.LL[0].V) return false;
    return true;
};

leilaoUtil.prototype.desenharLicitacoes = function(){
if (!this.settingLeilõesMostrarValores) return;
	var v=this.dadosActuais.LI;
	var html="<table class='tabela-licitacoes' style='width:450px'><tr><th>Data da Licitação</th><th>Valor</th><th>Nick</th><th>Overtime ?</th></tr>";
	for (i = 0; i < v.length; i++) {
		html+="<tr><td>"+ v[i].D + "</td><td>" +this.getValorFormatado(v[i].V)+ "</td>";
		if(v[i].N==this.iniNickName){html+="<td><b>" + v[i].N + "</b></td>"}else{html+="<td>" + v[i].N + "</td>"};
		if(v[i].O){html+="<td><span style='text-align:center'><img src='/userfiles/image/icons/overtime.png' /></span><td>"} else {html+="<td></td>"};
		html+="</tr>";
	};
	html+="</table>";
	$("#" + this.outputLicitacoesHistorico).html(html);
}

leilaoUtil.prototype.getValorFormatado= function(x){return "€ " + x + ",00";}

leilaoUtil.prototype.desenharValores= function(){
	var vi=this.dadosActuais.LL[0].V;
	var n=30;
		
	if (this.N >0 ){
		n=0;
		var i=0;
		var vMin=this.dadosActuais.LL[0].V;
		var v=0;
		$("#selValores option").each(function() {
			v= parseInt($(this).val());
			vi=v;
			if (v > 0 && v<=vMin){	
				$("#selValores")[0].remove(i);
				n++;
			} else{i++};
			//i++;
		});
	};
		
	if (this.dadosActuais.LL[0].E == 2) {
		var options = $("#selValores");
		if(this.N ==0)	options.append($("<option />").val(0).text("seleccionar"));
		for (i = 0; i < n; i++) {
			if (vi <= 90) {
				vi += 10;
			}
			else 
				if (vi <= 480) {
					vi += 20;
				}
				else 
					if (vi <=950) {
						vi += 50;
					}
					else {
						vi += 100;
					}
		options.append($("<option />").val(vi).text(this.getValorFormatado( vi)));
		};
	};

}

leilaoUtil.prototype.getLeiloes = function () {
    this.working = true;
    var url = this.getURLLeiloes();

    if (url.length == 0) {
        this.working = true;
        this.settingLeilõesOn = 0;
        return;
    };


    $.getJSON(url, function (json) {
        leilao.dadosActuais = json;
        leilao.desenharLeiloes();
        leilao.working = false;
    });
};

leilaoUtil.prototype.goLeiloes = function(){
	if (!this.working) {this.getLeiloes();};
    if(this.settingLeilõesOn){window.setTimeout("leilao.goLeiloes()", this.timer );} 
	else{
	$("#butLicitar").css('visibility','hidden');
	
	};
}


leilaoUtil.prototype.bind = function(){
	if (this.iniIDUtilizador == 0) {
		$("#butLicitar").click(function() {
			alert("Para licitar tem que fazer login.");
			return false;
		});
		
		$("#butLogin").click(function() {
			$("#operacao").val('login');
		});
		
		
	}else{
		
		$("#butLicitar").click(function() {
			if ($("#selValores").val()=='0') {
				$("#selValores").css({'border': '3px solid red'});
				alert("Tem que selecionar o valor da licitação");
				return false
			}
			$("#operacao").val('licitar');
		});
	};
}

function debug(x){
	var myDate=new Date();
	$("#debug").html( myDate.toGMTString()+ " - " +x );
}


$(document).ready(function() {

if (leilao.iniIDUtilizador > 0) {
    $("#leiloesRegisto").attr("href", "/pt/leiloes/myleiloes.aspx");
    $("#leiloesRegisto").html(leilao.iniNickName);

    $("#leiloesLogin").attr("href", "/pt/leiloes/sair.aspx");
    $("#leiloesLogin").html("Sair");
}

	if(leilao.iniIdLeilao>=0){
	leilao.bind();
	
		leilao.goLeiloes();
	}
});


