/**
 * @author Claudio Benech
 */

// Resets searchbox
function cleanSearch() {
	if ($('#searchwords').val() == 'Cerca nell\'archivio notizie') {
  	$('#searchwords').val('');
  }
	else if ($('#searchwords').val() == '') {
  	$('#searchwords').val('Cerca nell\'archivio notizie');
  }
}

// Checks string in searchbox before submitting
function submitSearch() {
	var searchwords = $('#searchwords').val();
	searchwords = $.trim(searchwords);
	if (searchwords == 'Cerca nell\'archivio notizie' || searchwords == '') {
		alert('Specifica del testo da cercare!');
		$('#searchwords').focus();
	}
	else {
		$('#searchnews').submit();
	}
}

// Gets Flickr gallery via AJAX
function callFlickr() {
	$.ajax({
		type: 'get',
	  url: 'flickr.php',
		error: function() {
			callFlickr();
		},
  	success: function(data) {
			$('#bottomright').removeClass('loading');
			var code = '';
			var i = 1;
			$('>rsp>photos>photo', data).each( function() {
				code += '<a href="http://www.flickr.com/photos/' + $(this).attr('owner') + '/' + $(this).attr('id') + '" title="' + $(this).attr('title') + '" target="_blank"><img class="pic';
				if (i != 5) {
					code += ' wrmargin';
					i++;
				}
				else {
					i = 1;
				}
				code += '" src="http://farm' + $(this).attr('farm') + '.static.flickr.com/' + $(this).attr('server') + '/' + $(this).attr('id') + '_' + $(this).attr('secret') + '_s.jpg" alt="pic' + $(this).attr('id') + '"/></a>';
			});
			$('#flickr').prepend(code);
			$('#gallery').show();
		}
	});	
}

function sendMail() {					   				   
	$(".error").hide();
	var hasError = false;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	
	var emailFromVal = $('#emailFrom').val();
	if (emailFromVal == '' || !emailReg.test(emailFromVal)) {
		$('#emailFrom').after('<span class="error">Devi inserire un indirizzo e-mail valido!</span>');
		hasError = true;
	}
	var nameVal = $('#name').val();
	if (nameVal == '') {
		$('#name').after('<span class="error">Devi inserire il tuo nome!</span>');
		hasError = true;
	}
	var messageVal = $('#message').val();
	if (messageVal == '') {
		$('#message').after('<span class="error">Devi inserire un messaggio!</span>');
		hasError = true;
	}
	if (hasError == false) {
		$('#sending').append('<img src="../images/loading.gif" alt="Loading" />');
		$.post(
			'sendmail.php',
			{ emailFrom: emailFromVal, name: nameVal, message: messageVal },
 			function(data) {
				$('#sending img').remove();
				$('#sending').text('Email inviata con successo!');
				setTimeout('tb_remove()', 3000);
 			}
		);
	}
}

// Init
$(document).ready(function(){
	callFlickr();   
});