
ClickMania = {
	BASE_HREF: document.getElementsByTagName("head")[0].getElementsByTagName("base")[0].href,
	interval_auctions: null,
	waitingReply: false,

	setServerTime: function(time) {
		if ($("#serverTime").html() != time) {
			$("#serverTime").html(time);
		}
	},

	Leiloes: {
		manager: [],

		add: function(codigo, tipo) {
			var found = false;
			for (var i = 0, t = this.manager.length; i < t; i++) {
				if (this.manager[i].codigo == codigo && this.manager[i].tipo == tipo) {
					found = true;
					break;
				}
			}
			if (found == false) {
				this.manager.push({
					codigo: codigo,
					tipo: tipo
				});
			}
		},

		remove: function(codigo) {
			var temp = [];
			for (var i = 0, t = this.manager.length; i < t; i++) {
				if (this.manager[i].codigo != codigo) {
					temp.push(this.manager[i]);
				}
			}
			this.manager = temp;
		},

		makeParams: function() {
			var params = [];
			for (var i = 0, t = this.manager.length; i < t; i++) {
				params.push(this.manager[i].codigo + this.manager[i].tipo);
			}
			return params.join(',');
		},

		requireData: function() {
			if (ClickMania.waitingReply == true) return;

			element = document.getElementById('scriptid');
			if (element != null) {
				element.parentNode.removeChild(element);
			}
			var params = this.makeParams();
			var url = ClickMania.BASE_HREF + (params.length ? 'auctions.php?auctions='+params+'&' : 'servertime.php?') + 't_=' + Math.random() * 20;

			element = document.createElement("script");
			element.src = url;
			element.type = "text/javascript";
			element.id = "scriptid";
			element.charset = "ISO-8859-1";

			if (document.all) {
				element.onreadystatechange = function() {
					if (element.readyState == 'loaded' || element.readyState == 'complete') {
						element.onreadystatechange = null;
						ClickMania.waitingReply = false;
					}
				};
			} else {
				element.onload = function() {
					ClickMania.waitingReply = false;
				};
			}

			ClickMania.waitingReply = true;
			document.getElementsByTagName("head")[0].appendChild(element);
		},

		f1: function(data) {
			jQuery.each (eval(data), function (i, auction) {
				ClickMania.setServerTime(auction.sd);

				var el = $("div[auction="+auction.c+"]");
				if (el) {
					var auctiontype = el.attr('auctiontype') || 'N';

					if (auction.f == true) {
						el.removeClass('ativo');
						$('#auction_'+ auction.c +'_time, #HIGHLIGHT_auction_'+ auction.c +'_time').html('00:00');
						$('#auction_'+ auction.c +'_bid, #HIGHLIGHT_auction_'+ auction.c +'_bid').css('display', 'none');
						$('#auction_'+ auction.c +'_finished, #HIGHLIGHT_auction_'+ auction.c +'_finished').css('display', 'block');
						$('#auction_'+ auction.c +'_time, #HIGHLIGHT_auction_'+ auction.c +'_time').removeClass('acabando');
						ClickMania.Leiloes.remove(auction.c);

						if (auction.g == true) {
							var url = ClickMania.BASE_HREF + 'leiloes/arremate/?leilao='+auction.c+'&iframe=true&width=700&height=300';
							$.prettyPhoto.open(url);
						}
					} else {
						if (auction.ls <= auction.st) {
							el.addClass('ativo');
							$('#auction_'+ auction.c +'_start, #HIGHLIGHT_auction_'+ auction.c +'_start').css('display', 'none');
							$('#auction_'+ auction.c +'_finished, #HIGHLIGHT_auction_'+ auction.c +'_finished').css('display', 'none');
							$('#auction_'+ auction.c +'_time, #HIGHLIGHT_auction_'+ auction.c +'_time').html(auction.t);
							if (parseInt(auction.t.replace(':', ''), 10) <= 10) {
								$('#auction_'+ auction.c +'_time, #HIGHLIGHT_auction_'+ auction.c +'_time').addClass('acabando');
							} else {
								$('#auction_'+ auction.c +'_time, #HIGHLIGHT_auction_'+ auction.c +'_time').removeClass('acabando');
							}
						} else {
							$('#auction_'+ auction.c +'_start_date, #HIGHLIGHT_auction_'+ auction.c +'_start_date').html(auction.m);
							$('#auction_'+ auction.c +'_start, #HIGHLIGHT_auction_'+ auction.c +'_start').css('display', 'block');
						}

						var valor = parseFloat(auction.v.replace(/[^0-9.,]/g, '').replace('.', '').replace(',', '.'));
						$('#auction_'+ auction.c +'_bid, #HIGHLIGHT_auction_'+ auction.c +'_bid').css('display', (((auction.p == '1' && auction.ls <= auction.st && auction.pt != '00:00') || (auction.p == '0' && auction.t != '00:00')) ? 'block' : 'none'));

						if (auction.p) {
							$('#auction_'+ auction.c +'_inactivity').html(auction.pt);

							$('#auction_'+ auction.c +'_numregistry, #HIGHLIGHT_auction_'+ auction.c +'_numregistry').css('display', (auction.ls > auction.st ? 'block' : 'none'));
							$('#auction_'+ auction.c +'_registry, #HIGHLIGHT_auction_'+ auction.c +'_registry').css('display', (auction.pi ? 'block' : 'none'));
						}

						var elPreco = $('#auction_'+ auction.c +'_price, #HIGHLIGHT_auction_'+ auction.c +'_price');
						if (elPreco.is(':visible') && elPreco.html() != auction.v) {
							elPreco.effect("highlight", {color:'#FFCC00'}, 500);
						}
						elPreco.css('display', ((auction.p == '0' || (auction.p == '1' && auction.ls <= auction.st)) ? 'block' : 'none')).html(auction.v);

						$('#auction_'+ auction.c +'_user, #HIGHLIGHT_auction_'+ auction.c +'_user').css('display', 'block').html(auction.u[0]);

						if (auctiontype == 'F') {
							var elPercentage = $('#auction_'+ auction.c +'_percentage, #HIGHLIGHT_auction_'+ auction.c +'_percentage');
							if (elPercentage) {
								elPercentage.html( number_format(100 - ((valor * 100) / auction.vm), 2, ',', '.') +'%');
							}
	
							var elLastBids = $('#auction_'+ auction.c +'_lastbids');
							if (elLastBids) {
								elLastBids.find('li').remove();
								for (var i = 0, t = auction.u.length; i < t; i++) {
									elLastBids.append('<li><span>'+ auction.u[i] +'</span><span>R$ '+ number_format(valor, 2, ',', '.') +'</span></li>');
									valor = valor - 0.01;
								}
							}
						}

						if (auction.p && auctiontype == 'F') {
							var elParticipants = $('#auction_'+ auction.c +'_participants');
							var participants = auction.pp.length;
							if (elParticipants) {
								elParticipants.find('li').remove();
								for (var i = 0, t = auction.pp.length; i < t; i++) {
									var cls = (auction.pp[i].e ? 'class="eliminado"' : null);
									elParticipants.append('<li '+cls+'>'+ auction.pp[i].l +'</li>');

									if (auction.pp[i].e) participants = participants - 1;
								};
							}
							$('#auction_'+ auction.c +'_bettors').html(participants);
						}
					}
				}
			});
		}
	},

	Lance: function(auction) {
		$.ajax({
			url: ClickMania.BASE_HREF + 'bid.php?auction='+auction,
			cache: false,
			type: 'get',
			dataType: 'json',
			success: function(retorno) {
				if (retorno.message) {
					alert(retorno.message);
				} else {
					$('#userLances').html(retorno.lances);
				}
			}
		});
	},

	doLogin: function(usuario) {
		$('#userData').css('display', (usuario == null ? 'none' : 'block'));
		$('#frmLogin').css('display', (usuario == null ? 'block' : 'none'));
		$('#userName').html(usuario.nome);
		$('#userLances').html(usuario.lances);
		if(usuario.termo == 'false') {
			document.location.href = 'usuarios/reaceitacao';
		}
	},

	Depoimento: {
		post: function(obj, leilao, acao) {
			$.ajax({
				url: ClickMania.BASE_HREF + 'usuarios/depoimento',
				data: {leilao: leilao, acao: acao}
			});

			var parent = obj.parentNode;
			parent.removeChild( obj );
			if (!parent.children.length) {
				parent.parentNode.removeChild(parent);
			}
		},

		adiar: function(obj, leilao) {
			this.post(obj, leilao, 1);
		},

		ignorar: function(obj, leilao) {
			this.post(obj, leilao, 2);
		}
	}
};

$(document).ready(function() {
	var itens = $('div[auction]');
	var leiloes = [];
	$.each(itens, function(index, value) {
		ClickMania.Leiloes.add(value.getAttribute('auction'), (value.getAttribute('auctiontype') || 'N'));
	});
	ClickMania.interval_auctions = window.setInterval(function() {
		ClickMania.Leiloes.requireData();
	}, "1000");
	ClickMania.Leiloes.requireData();

	$('a:[href*=cadastro],a:[href*=minha-conta]').click(function() {
		window.clearInterval(ClickMania.interval_auctions);
	});

	$("bug-init").prettyPhoto();
});
