// Document is ready
$(document).ready(function () {
	
	// Ricarica gli annunci
	ads.reload();	
			
	// Mostra le FAQ
	$("<h3></h3>").html("<a href='#' class='showfaq'>Leggi le FAQ</a>").appendTo("#header");
	$('#header a.showfaq').livequery("click", function(){
    ads.faqid = 0;
		ads.header();
	});
	
	// Mostra il link di modifica per gli annunci
	$("#ads div:not(#g0) p").livequery(function() {
																		 
    $(this) 
      .hover(function() { 
			  $(this).prepend($("<a href=\"#\" id=\"editLink\" title=\"Modifica questo annuncio\"><img src=\"img/edit.gif\" alt=\"Modifica\" /></a>"));
      }, function() { 
				$("#editLink").remove();
    }); 
																		 
	});
	
	// Load the edit form using ajax
	$('#editLink, #editForm input:eq(0)').livequery("click", function (e) {
		e.preventDefault();
		
		loc = $("#editLink").parent().attr("id");
		
		$.get("edit.php", { loc: loc }, function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				overlayId: 'edit-overlay',
				containerId: 'edit-container',
				overlay: 80,
				onOpen: edit.open,
				onShow: edit.show,
				onClose: edit.close
			});
		});
	});
		
	// Apre un link ad un sito esterno
	$("#ads a.external").livequery("click", function () {
    ads.page("redirect.php", {url: $(this).attr("href")});
		return false;
  });
	
	// Apre un link in una nuova finestra
	$("a.newWindow").livequery("click", function () {
		var newWindow = window.open($(this).attr("href"), '_blank'); 
		newWindow.focus(); 
		return false; 
  });
	
	// Autocompletamento
	$("#edit-site").livequery("blur", function (e) {
		edit.autocomplete(this);													 
	});
	
	// Aiuto
	$('#faqLink').livequery("click",function(){
		ads.page("faq.php");
    return false;
	});
	// Disclaimer
	$('#disclaimerLink').livequery("click",function(){
		ads.page("disclaimer.php");
		return false;
	});
	// Torna agli annunci
	$('#adsLink,.goHome').livequery("click", function(){
		ads.page("ads.php");
		return false;
  });
	
	// Description Max Length
	$("#edit-desc").livequery("keypress", function (e) {
    return (e.which == 8 ? true : (this.value.length <= 50));
	});

	// preload images
	var img = ['edit.gif','form_bottom.gif','form_top.gif','form_top_ie.gif','loading.gif','loading2.gif'];
	$(img).each(function () {
		var i = new Image();
		i.src = 'img/' + this;
	});
});

// Aggiorna gli annunci o visualizza alcune pagine del sito
var ads = {
	loading: "Caricamento in corso....",
	cpage: "ads.php",
	timeout: 30000,
	reload: function(runOnce) {
		if (ads.cpage == "ads.php") {
			
      var nonce = Math.floor(Math.random()*100);

	    $.get("ads.php?nonce="+nonce, function (data) {
		    $("#main").html(data);	
				if(!runOnce)
		      setTimeout("ads.reload()", ads.timeout);
	    });
		}
	},
	page: function(pag, pag_data){
    scroll(0,0);
		$("#main").html(ads.loading);	
		
		ads.cpage = pag;
		
		if(pag_data)
	    $.post(pag, pag_data, function (data) {
		    $("#main").html(data);	
	    });
		else
	    $("#main").load(pag + " div:eq(0)");
		
		ads.faqid = -1;
		ads.header();
	},
	faqid: 0,
	header: function(){
		if(ads.cpage == "ads.php") {
			var faqs = new Array();
			
			function Faq(q, a) {
				this.q = q;
				this.a = a;
				return this;
			}
			
			faqs[0] = new Faq("Che cos'&egrave; RubaSpazietto?", "RubaSpazietto &egrave; una directory che pubblicizza i siti inseriti mostrandoli ad altri inserzionisti.");
			faqs[1] = new Faq("Cosa cambia da una normale directory?", "Gli spazi disponibili sono solo 26. Inserendo un sito ruberai lo spazio ad un altro inserzionista.");
			faqs[2] = new Faq("Come faccio ad inserire un sito?", "Posizionati con il cursore su un annuncio e fai click sulla matita che appare.");
			faqs[3] = new Faq("Perch&egrave; non posso modificare l'annuncio centrale?", "L'annuncio centrale &egrave; riservato al sito pi&ugrave; pubblicato della  settimana precedente.");
			faqs[4] = new Faq("E' ammesso qualunque sito?", "No, sono esclusi siti illegali o che ledano la morale comune. <a href='#' id='disclaimerLink'>Leggi il Regolamento</a>.");
			faqs[5] = new Faq("Dove posso trovare ulteriori informazioni?", "Ulteriori informazioni sono disponibili nella pagina delle <a href='#' id='faqLink'>Domande Frequenti</a>.");

			var id = ads.faqid;
			
			$("#header").empty();
			
			if(id < faqs.length && id > -1) {
			  ads.faqid = id + 1;
				
				$("<h3></h3>").html(faqs[id].q).appendTo("#header");
				$("<p></p>").html(faqs[id].a).appendTo("#header");
				
				setTimeout("ads.header()", 8000);
			} else {
				$("<h3></h3>").html("<a href='#' class='showfaq'>Leggi le FAQ</a>").appendTo("#header");
			}
			
		} else {
			$("#header").empty();
		}
	}
}

var edit = {
	message: null,
	open: function (dialog) {
		// add padding to the buttons in firefox/mozilla
		if ($.browser.mozilla) {
			$('#edit-container .edit-button').css({
				'padding-bottom': '2px'
			});
		}
		// input field font size
		if ($.browser.safari) {
			$('#edit-container .edit-input').css({
				'font-size': '.9em'
			});
		}

		var title = $('#edit-container .edit-title').html();
		$('#edit-container .edit-title').html('Caricamento...');
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200, function () {
					$('#edit-container .edit-content').animate({
						height: 260
					}, function () {
						$('#edit-container .edit-title').html(title);
						$('#edit-container form').fadeIn(200, function () {
							$('#edit-container #edit-title').focus();

							// fix png's for IE 6
							if ($.browser.msie && $.browser.version < 7) {
								$('#edit-container .edit-button').each(function () {
									if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
										var src = RegExp.$1;
										$(this).css({
											backgroundImage: 'none',
											filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
										});
									}
								});
							}
						});
					});
				});
			});
		});
	},
	show: function (dialog) {
		$('#edit-container .edit-send').click(function (e) {
			e.preventDefault();
			// validate form
			if (edit.validate()) {
				$('#edit-container .edit-message').fadeOut(function () {
					$('#edit-container .edit-message').removeClass('edit-error').empty();
				});
				$('#edit-container .edit-title').html('Invio in corso...');
				$('#edit-container form').fadeOut(200);
				$('#edit-container .edit-content').animate({
					height: '80px'
				}, function () {
					$('#edit-container .edit-loading').fadeIn(200, function () {
						$.ajax({
							url: 'edit.php',
							data: $('#edit-container form').serialize() + '&action=send',
							type: 'post',
							cache: false,
							dataType: 'html',
							complete: function (xhr) {
								$('#edit-container .edit-loading').fadeOut(200, function () {
									$('#edit-container .edit-title').html('Operazione completata!');
									$('#edit-container .edit-message').html(xhr.responseText).fadeIn(200);
								});
							},
							error: edit.error
						});
					});
				});
			}
			else {
				if ($('#edit-container .edit-message:visible').length > 0) {
					var msg = $('#edit-container .edit-message div');
					msg.fadeOut(200, function () {
						msg.empty();
						edit.showError();
						msg.fadeIn(200);
					});
				}
				else {
					$('#edit-container .edit-message').animate({
						height: '30px'
					}, edit.showError);
				}
				
			}
		});
	},
	close: function (dialog) {
		ads.reload(true);
		$('#edit-container .edit-message').fadeOut();
		$('#edit-container .edit-title').html('Chiusura in corso...');
		$('#edit-container form').fadeOut(200);
		$('#edit-container .edit-content').animate({
			height: 40
		}, function () {
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		});
	},
	error: function (xhr) {
		alert(xhr.statusText);
	},
	validate: function () {
		edit.message = '';
		if (!$('#edit-container #edit-title').val()) {
			edit.message += 'Inserire un titolo. ';
		}
		
		var site = $('#edit-container #edit-site').val();
		if (!site) {
			edit.message += 'Inserire un indirizzo. ';
		}
		else {
			if (!edit.validateSite(site)) {
				edit.message += 'Indirizzo non valido. ';
			}
		}

		if (!$('#edit-container #edit-desc').val()) {
			edit.message += 'Inserire una descrizione. ';
		}
		
		if ($('#edit-container #edit-desc').val().length > 50) {
			edit.message += 'Inserire una desc. pi&ugrave; breve. ';
		}

		if (edit.message.length > 0) {
			return false;
		}
		else {
			return true;
		}
	},
	validateSite: function (site) {
		if (!/^http:\/\/(www\.)?([a-zA-Z0-9_\-\.]+\.[a-zA-Z0-9_\-\.]+)\/?(.*)/.test(site))
			return false;	

		return true;
	},
	showError: function () {
		$('#edit-container .edit-message')
			.html($('<div class="edit-error">').append(edit.message))
			.fadeIn(200);
	},
	autocomplete: function (element) {
		var ctitle = $("#edit-title").val();
		var cdesc = $("#edit-desc").val();
		
		if(!ctitle || !cdesc) {
			
			$("#edit-desc").css({backgroundImage: "url(img/loading2.gif)"});																			
			$.ajax({
				type: "POST",
				url: "autocomplete.php",
				dataType: "xml",
				data: {url: element.value},
				success: function(xml) {
					 var title = $(xml).find('title').text();
					 var desc = $(xml).find('desc').text();
					 
					 if(title && !ctitle) $("#edit-title").val(title);
					 if(desc && !cdesc) $("#edit-desc").val(desc);
					 
					 $("#edit-desc").css({backgroundImage: "none"});																			
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$("#edit-desc").css({backgroundImage: "none"});																			
					alert(textStatus);
				}
		  });
			
		}
	}
	
};