
var index_contatoreLength = 6;

function index_initContatori() {
    $.preload([
        "images/header/counter-digit0-background.gif",
        "images/header/counter-digit1-background.gif",
        "images/header/counter-digit2-background.gif",
        "images/header/counter-digit3-background.gif",
        "images/header/counter-digit4-background.gif",
        "images/header/counter-digit5-background.gif",
        "images/header/counter-digit6-background.gif",
        "images/header/counter-digit7-background.gif",
        "images/header/counter-digit8-background.gif",
        "images/header/counter-digit9-background.gif"
    ], {
        loaded_all: function(loaded, total) {
			var interval = null;
			start();
			function start() {
				if(interval == null) {
					interval = setTimeout(loop, 0);
				} else {
					clearInterval(interval);
					interval = setTimeout(loop, 2000);
				}
			}
			function loop() {
				$.ajax({
					url: "index.contatori.jsp",
					data: null,
					cache: false,
					async: true,
					type: "GET",
					dataType: "xml",
					timeout: 0,
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						start();
					},
					success: function(xml, textStatus) {
						var totaleAnnunciAttivi = parseInt($(xml).find("totaleAnnunciAttivi").text());
						var totaleAnnunciScambiati = parseInt($(xml).find("totaleAnnunciScambiati").text());
						index_aggiornaContatore($("div.div-counters div.div-counter.div-counter-annunci-attivi"), totaleAnnunciAttivi);
						index_aggiornaContatore($("div.div-counters div.div-counter.div-counter-annunci-scambiati"), totaleAnnunciScambiati);
						start();
					}
				});
			}
        }
    });
}

function index_aggiornaContatore(contatore, numero) {
	var numeroCorrente = 0;
	contatore.find("ul li").each(function(index) {
		numeroCorrente += (Math.pow(10, (index_contatoreLength - index - 1)) * parseInt($(this).attr("title")));
	});
	if(numero != numeroCorrente) {
		contatore.find("ul li").each(function(index) {
			var cifraLi = $(this);
			var cifraCorrente = parseInt(cifraLi.attr("title"));
			var cifra = Math.floor((numero - (Math.floor(numero / Math.pow(10, (index_contatoreLength - index))) * Math.pow(10, index_contatoreLength - index))) / Math.pow(10, (index_contatoreLength - index - 1)));
			var interval = null;
			start();
			function start() {
				if(interval == null) {
					interval = setTimeout(loop, 0);
				} else {
					clearInterval(interval);
					interval = setTimeout(loop, 50);
				}
			}
			function loop() {
				cifraCorrente = ((cifraCorrente >= 9) ? 0 : (cifraCorrente + 1));
				cifraLi.removeClass();
				cifraLi.addClass("li-digit" + cifraCorrente);
				cifraLi.attr("title", cifraCorrente);
				if(cifraCorrente != cifra) {
					start();
				}
			}
		});
	}
}

function index_initMosaic() {
	$('div.page_div-mosaic div.page_div-mosaic-box').hover(function() {
		$(this).addClass("page_div-mosaic-hover");
	},
	function() {
		$(this).removeClass("page_div-mosaic-hover");
	});
	var interval = null;
	start();
	function start() {
		if(interval != null) {
			clearInterval(interval);
		}
		interval = setTimeout(loop, 2000);
	}
	function loop() {
		$.ajax({
			url: "index.immagine.jsp",
			data: null,
			cache: false,
			async: true,
			type: "GET",
			dataType: "html",
			timeout: 0,
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				start();
			},
			success: function(html, textStatus) {
				$.preload([
					$(html).find("img").attr("src")
				], {
					loaded_all: function(loaded, total) {
						var randomBox = jQuery("div.page_div-mosaic div.page_div-mosaic-box:not(.page_div-mosaic-hover)").get().sort(function() {
							return Math.round(Math.random()) - 0.5;
						}).slice(0, 1);
						$(randomBox).animate({
							opacity: 0
						}, 1000, function() {
							$(randomBox).find("a").qtip("hide").qtip("destroy");
							$(randomBox).html(html);
							index_initTooltip($(randomBox).find("a"), $(randomBox).find("img").attr("longdesc"));
							$(randomBox).animate({
								opacity: 1
							}, 1000, function() {
								start();
							});
						});
					}
				});
			}
		});
	}
}

function index_initTooltips() {
	$('div.page_div-mosaic div.page_div-mosaic-box a').each(function() {
		index_initTooltip($(this), $(this).find("img").attr("longdesc"));
	});
}

function index_initTooltip(tooltipLink, tooltipUrl) {
	tooltipLink.qtip({
		content: {
			url: tooltipUrl,
			method: "get"
		},
		style: {
			padding: 5,
			background: '#ffffff',
			color: '#000000',
			textAlign: 'left',
			border: {
				width: 1,
				radius: 3,
				color: '#dddddd'
			},
			tip: 'bottomLeft',
			name: 'cream'
		},
		position: {
			corner: {
				target: 'center',
				tooltip: 'bottomLeft'
			}
		},
		hide: {
			fixed: true,
			when: {
				event: 'mouseout'
			}
		}
	});
}

function index_initRicercaComuneAutoComplete() {
	$("#input-comune").autocomplete({
		source: function(request, response) {
			$.ajax({
				url: "autocomplete/comuni.jsp?nome=" + $("#input-comune").val(),
				dataType: "xml",
				success: function(xml) {
					var data = $("comune", xml).map(function(item) {
						return {
							id: $("id", this).text(),
							nome: $("nome", this).text(),
							cap: $("cap", this).text(),
							idProvincia: $("idProvincia", this).text(),
							nomeProvincia: $("nomeProvincia", this).text(),
							idRegione: $("idRegione", this).text(),
							nomeRegione: $("nomeRegione", this).text(),
							value: $("nome", this).text(),
							label: $("nome", this).text() + " (" + $("idProvincia", this).text() + ")"
						};
					});
					response(data);
				}
			});
		},
		minLength: 1,
		autoFocus: true,
		change: function(event, ui) {
			if(!ui.item) {
				$(this).val("");
				$("#input-idProvincia").val("");
				return false;
			}
		},
		select: function(event, ui) {
			$(this).val(ui.item.nome);
			$("#input-idProvincia").val(ui.item.idProvincia);
		}
	});
}

function index_initRicercaWarning() {
	$("#form-ricerca").submit(function() {
		if($("#input-idProvincia").val() == "") {
			alert("Inserisci il nome della tua cittą!");
			return false;
		}
		return true;
	});
}

(function($) {
	var imgList = [];
	$.extend({
		preload: function(imgArr, option) {
			var setting = $.extend({
				init: function(loaded, total) {},
				loaded: function(img, loaded, total) {},
				loaded_all: function(loaded, total) {}
			}, option);
			var total = imgArr.length;
			var loaded = 0;
			setting.init(0, total);
			for(var i in imgArr) {
				imgList.push($("<img />")
					.attr("src", imgArr[i])
					.load(function() {
						loaded++;
						setting.loaded(this, loaded, total);
						if(loaded == total) {
							setting.loaded_all(loaded, total);
						}
					})
				);
			}
			
		}
	});
})(jQuery);

$(document).ready(function() {
	index_initContatori();
	index_initMosaic();
	index_initTooltips();
	index_initRicercaComuneAutoComplete();
	index_initRicercaWarning();
	$('input#input-nome').focus();
});

