/**
 * @author Pietro
 */
// Definisco la console, per gli ambienti privi di firebug.
if (typeof console == 'undefined') {
	console = new Object;
	console.trace = function() {};
	console.log = function() {};
	console.debug = function() {};
	console.info = function() {};
	console.warn = function() {};
	console.error = function() {};
	console.time = function() {};
	console.timeEnd = function() {};
	console.count = function() {};
}

/** HOME SLIDESHOW**/
var effetti = ['fade','fadeZoom','scrollDown','scrollLeft','scrollHorz','shuffle','slideX','slideY','turnUp','turnRight','zoom'];
function initSlideShow(){
	var effetto = Math.floor(Math.random()*effetti.length);
	$(".slideshow").cycle({ 
	    fx: effetti[effetto] 
	});

}
/** END HOME SLIDESHOW**/

/** GOOGLE CALENDAR**/
function initGoogleCalendar(){
	try{
		google.load("gdata", "1");
		isGAPIenalbled = true;
	}catch (e){
		isGAPIenalbled = false;
	}

}

function handleMyFeed(myResultsFeedRoot) {
	 var dataAttuale = new Date();
	 var eventi = myResultsFeedRoot.feed.getEntries();
	 $('#eventi').append('<ul>');
	 var quando;
	 var dove;
	 var dataEvento;
	 var eventiPresenti = false;
	 for (i = 0; i < eventi.length; i++){
	 	 quando = eventi[i].getTimes();
	 	 dove = eventi[i].getLocations();
		 dataEvento = quando[0].getStartTime().getDate();
		 if (dataEvento.getTime() > dataAttuale.getTime()){
		 	eventiPresenti = true;
	 	 	$('#eventi ul')
				.prepend(
					'<li>' + 
						'<span>' + settimana[dataEvento.getUTCDay()] + ' ' + dataEvento.getUTCDate() + ' ' + mesi[dataEvento.getUTCMonth()] + ' ' + (dataEvento.getFullYear()) +  ' - ' + eventi[i].getTitle().getText() + '</span>' +
						'<span class="leggiDettagliEvento"> Leggi dettagli</span>' +
						'<blockquote>' +
							 'Quando: ' + dataEvento.getUTCDate() + ' ' + mesi[dataEvento.getUTCMonth()] + ' ' + (dataEvento.getFullYear()) + 
							 ' Ore: ' + dataEvento.toLocaleTimeString().substring(0,5) +
							 '<br>' +  
							 'Dove: ' + dove[0].getValueString() + 
							 '<br>' +  
							 eventi[i].getContent().getText() + 
						 '</blockquote>' +
					'</li>'
				);
		 }
	 }
	 if (!eventiPresenti){
	 	//	messaggio di cortesia per assenza di eventi in calendario
	 	 	$('#eventi ul').remove();
			$('#eventi').append(msgCortesiaCalendario);
	 }
	$('blockquote').hide();
	 var apriDettaglio = function (){
	 	$(this).next().show('fast');
		$(this).prev().addClass('titoloEvento');
		$(this).html(' Chiudi dettagli');
	 };
	 var chiudiDettaglio = function (){
	 	$(this).next().hide('fast');
		$(this).prev().removeClass('titoloEvento');
		$(this).html(' Leggi dettagli');
	 }
	 $('.leggiDettagliEvento').toggle(apriDettaglio, chiudiDettaglio);
}

function handleError(e) {
  alert("There was an error!");
  alert(e.cause ? e.cause.statusText : e.message);
}

function setupMyService() {
  var myService =
    new google.gdata.calendar.CalendarService('Prova');
  return myService;
}

function getMyFeed() {
  myService = setupMyService();
  myService.getEventsFeed(feedUrl, handleMyFeed, handleError);
}			
/** END GOOGLE CALENDAR**/

//	restituisce il path dell'immagine grande a partire dal path della thumb
function getFullImage(srcThumb){
	var percorso = srcThumb;
	var ultimoSlash;
	for (i = 0; i<2; i++){
		ultimoSlash = percorso.lastIndexOf('/');
		percorso = srcThumb.substring(0,ultimoSlash);
	}
	//	nome del file selezionato
	imgSelezionata = srcThumb.substring(srcThumb.lastIndexOf('/')+1,srcThumb.length);
	imgSelezionata = percorso + '/images/' + imgSelezionata;
	return imgSelezionata;
}

function getBrowser(){
	var versioni = new Array();
	versioni = navigator.appVersion.split(';');
	if(navigator.appName=="Microsoft Internet Explorer"){
		if (versioni[1]== ' MSIE 7.0')
		  	return 'IE7';
		else
		  	return 'IE6';
	}
	else if(navigator.appName=="Netscape"){
	  	return 'Firefox2'
 	}

}

/** CHIERICHETTI**/
function insertPersona(object){
	var clone = $templateImgTeaser.clone();
	var imgPersona = $("img",object).text();
	$("a span",clone).html($("nome",object).text());
	$("a img",clone).attr("alt",$("nome",object).text());
	if (imgPersona != null && imgPersona != ""){
		$("a img",clone).attr("src",$("img",object).text());
	}
	$(".temp td").append(clone);	
}

function loadCalendarioChierichetti(selector){
	$table = $(selector + " tbody");
	$templateImgTeaser = $("<div class=\"imgteaser\"><a href=\"#\"><img src=\"img/blank_fototessera.jpg\" alt=\"Daim Graffiti\" width=\"70\" height=\"70\"/><span class=\"more\">Edoardo S.</span></a></div>");
	$.ajax({
		type: "GET",
		url: 'chierichetti.xml',
		error: function(data){
			$(selector + " tbody").html("<tr><td>Nessun calendario disponibile</td></tr>");
		},
		success: function(data){
			$("giorno", data).each(function(){
				$table.append("<tr><td class=\"giorno\">" + $(this).attr("descrizione") + "</td></tr>");
				$("messa",this).each(function(){
					var gruppo = $(this).attr("gruppo");
					$table.append("<tr><td class=\"messa\">Ore " +  $(this).attr("ora")  + $(this).attr("descrizione") + "</td></tr>");
					$("<tr class=\"temp\"><td class=\"turno-chier\"></td></tr>").appendTo($table);
					
					//	inserisce gli elementi di un gruppo nella tabella
					$("gruppo[codice=" + gruppo + "] persona",data).each(function(){
						insertPersona(this);
					})
					$("persona",this).each(function(){
						insertPersona(this);						
					});						
					$(".temp").removeClass("temp");
				});
			});
		}
	});
}
/** END CHIERICHETTI**/
var animationSpeed = 300;

/** FOTOGALLERY **/
function initPhotogallery(){
		//asssegna le proprietà per l'animazione
		$(".sottoMenuLiv2").css({position: 'relative', left: '-119px'});
		$(".sottoMenuLiv3").css({position: 'relative', left: '-259px'});
 
		// nasconde gli elementi non visibili inzialmente
		$('.navigazioneFoto').hide();
		$('.block')	.hide();
		$('.loading').hide();
		$('.sottoMenuLiv2').hide();
		$('.sottoMenuLiv3').hide();
		// gestisce la gif di caricamento
		$('.loading').ajaxStart(function(){
			$('.loading').show();
		});
		$('.loading').ajaxStop(function(){
			$('.loading').hide();
		});
		
		//** definisce l'azione da compiere per aprire i sottomenu di II livello livello
		$('.apriMenuLiv2').click(function(e){
			e.preventDefault();
			$('.sottoMenuLiv2').css({left: '-119px'}).hide();
			$('.sottoMenuLiv3').css({left: '-259px'}).hide();
			menuLiv2 = $(this).attr('rel');
			$('.apriMenuLiv2').removeClass('voceSelezionata');
			$('.apriMenuLiv3').removeClass('voceSelezionata');
			$(this).addClass('voceSelezionata');
			$('#' + menuLiv2 + '.sottoMenuLiv2').show().animate({left: '0px'},animationSpeed);
		});

		//** definisce l'azione da compiere per aprire i sottomenu di III livello livello
		$('.apriMenuLiv3').click(function(e){
			e.preventDefault();
			$('.sottoMenuLiv3').css({left: '-259px'}).hide();
			menuLiv3 = $(this).attr('id');
			$('.apriMenuLiv3').removeClass('voceSelezionata');
			$(this).addClass('voceSelezionata');
			$('.sottoMenuLiv3#' + menuLiv2 + '_' + menuLiv3).show().animate({left: '0px'},animationSpeed);
		});
		
		//	chiamata AJAX per il caricamento della fotoGallery
		$('.voceMenu').click(function (e){
			e.preventDefault();
			var srcThumb;
			var nomeImg;
			var i;
			var title = $(this).html();
			pathXml = $(this).attr('name');
			$.get(pathXml, function(fotoGallery){
				i = 1;
				$("#gallery-title").remove();
				$(".elencoFoto").before("<h1 id=\"gallery-title\" class=\"block\">" + title + "</h1>");
				$('.fotoSelezionata,.elencoFoto').empty();
				nomeAlbum = $(fotoGallery).find('albumName').text();
				albumItemCount = $(fotoGallery).find('albumItemCount').text();
				rootAlbum = $(fotoGallery).find('albumCaption').text();
				$('.block').empty().append(nomeAlbum);
				//	carica le thumb della fotoGallery
				$(fotoGallery).find('images').find('image').each(function(j){
					srcThumb = $(this).find('itemThumbnailImage').text();
					nomeImg = $(this).find('itemName').text();
					$('.elencoFoto').append('<a class="pirobox_gall" href="'+ getFullImage(rootAlbum + srcThumb) +'" title="'+ nomeImg +'"><img id="'+ (j+1) +'" src="'+ rootAlbum + srcThumb +'" title="'+ nomeImg +'" alt="'+ nomeImg +'" border="0" /></a>');
				});
				enablePiroBox();

			});
		});
}

/** NEW PIROBOX GALLERY **/
function enablePiroBox(){
	$('.piro_overlay,.pirobox_content').remove();
	$(".elencoFoto").piroBox({
		my_speed: 300, //animation speed
		bg_alpha: 0.5, //background opacity
		radius: 4, //caption rounded corner
		scrollImage : false, // true == image follows the page _|_ false == image remains in the same open position
		                   // in some cases of very large images or long description could be useful.
		pirobox_next : 'piro_next', // Nav buttons -> piro_next == inside piroBox , piro_next_out == outside piroBox
		pirobox_prev : 'piro_prev',// Nav buttons -> piro_prev == inside piroBox , piro_prev_out == outside piroBox
		close_all : '.piro_close',// add class .piro_overlay(with comma)if you want overlay click close piroBox
		slideShow : 'slideshow', // just delete slideshow between '' if you don't want it.
		slideSpeed : 3 //slideshow duration in seconds(3 to 6 Recommended)
  	});
}
/** END FOTOGALLERY **/
