$('html').attr('class','js');

// ##########
// FUNZIONI
// ##########

// Funzione per la troncatura del testo del feed troppo lungo
(function($){
	$.fn.jTruncate = function(options) {
	   
		var defaults = {
			length: 300,
			minTrail: 20,
			moreText: "more",
			lessText: "less",
			ellipsisText: "...",
			moreAni: "",
			lessAni: ""
		};
		
		var options = $.extend(defaults, options);
	   
		return this.each(function() {
			obj = $(this);
			var body = obj.html();
			
			if(body.length > options.length + options.minTrail) {
				var splitLocation = body.indexOf(' ', options.length);
				if(splitLocation != -1) {
					// truncate tip
					var splitLocation = body.indexOf(' ', options.length);
					var str1 = body.substring(0, splitLocation);
					var str2 = body.substring(splitLocation, body.length - 1);
					obj.html(str1 + '<span class="truncate_ellipsis">' + options.ellipsisText + 
						'</span>' + '<span class="truncate_more" style="display:none">' + str2 + '</span>');
					
					// insert more link
					obj.append(
						'<div class="clearboth">' +
							'<a href="#" class="truncate_more_link">' + options.moreText + '</a>' +
						'</div>'
					);

					// set onclick event for more/less link
					var moreLink = $('.truncate_more_link', obj);
					var moreContent = $('.truncate_more', obj);
					var ellipsis = $('.truncate_ellipsis', obj);
					moreLink.live( 'click', function() {
						if(moreLink.text() == options.moreText) {
							moreContent.fadeIn(options.moreAni).css('display','');
							moreLink.text(options.lessText);
							ellipsis.hide();
						} else {
							moreContent.fadeOut(options.lessAni).css('display','none');
							moreLink.text(options.moreText);
							ellipsis.show();
						}
						return false;
				  	});
				}
			} // end if
			
		});
	};
})(jQuery);

// Funzione che crea il widget con le notizie dai vicariati prese dai feed di diweb tramite YQL
function diwebFeedWidget ( feed_url, num_of_items, target, title ) {
	// feed_url: indirizzo del feed RSS di diweb da utilizzare
	// num_of_items: stringa con il numero di notizie da recuperare
	// target: identificatore CSS dell'elemento nel quale inserire il widget
	// title: il testo da usare in accompagnamento all'icona del feed
	var query = "select * from feed where url='" + feed_url + "' LIMIT " + num_of_items;
	var url = "http://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(query) + "&format=json&callback=?";
	
	// Creo ed inserisco il contenitore per i feed
	$( target ).append('<div id="diweb-feed"><div id="diweb-feed-inner"></div><div class="widget-title"><a id="rss-ico" href="' + feed_url + '" title="Abbonati al feed RSS con le notizie dai vicariati della Diocesi di Padova"><img src="/s2ewdiocesipadova/s2magazine/css/0/images_dioc/rss16.png" alt="RSS" />' + title + '</a></div></div>')
	
	$.getJSON ( url, function(feeds_obj) {
		if (feeds_obj.query.results) {
			$.each( feeds_obj.query.results.item, function () {
				var titolo = this.title;
				var data = new Date(this.pubDate);
				var a_data = Array (data.getDate().toString(), (data.getMonth() + 1).toString(), data.getFullYear().toString(), data.getHours().toString(), data.getMinutes().toString() );
				// aggiungo uno 0 di fronte a data ed ore nel caso di cifre di una sola lettera
				for (n = 0; n < a_data.length; n++) {
					if (a_data[n].length == 1) {
						a_data[n] = "0" + a_data[n];
					};
				};
				var testo = '';
				// $(this.description) è un oggetto contenente paragrafi p, nodi di testo vuoti (null) e div.
				// Posso selezionare cosa tenere effettuando un controllo su ciascun elemento dell'oggetto.
				// Se il codice html di this.description è stato processato convertendo i caratteri in entitè,
				// e contiene la sequenza &amp;ldquo; allora salto il ciclo che altrimenti restituirebbe un errore
				if ( !/(&amp;ldquo;)/.test(this.description) ) {
					$( this.description ).each( function () {
						var tmp = $.trim ($(this).html());
						if ( tmp && !/(www.difesapopolo.it|Leggi tutto|^\s|^&nbsp;)/.test(tmp) ) {
							testo += tmp + ' ';
						};
					});
				} else {
					testo = this.description;
				};
				var indirizzo = this.link;
				var html = '<div class="item"><div class="line1"><span class="pubdate">' + a_data[0] + '/' + a_data[1] + '/' + a_data[2] + '</span> - <span class="title"><a href="' + indirizzo + '">' + titolo + '</a></span></div><div class="line2"><div class="description">' + testo + '</div></div></div>';
				// var html = '<div class="item"><div class="line1"><span class="pubdate">' + a_data[0] + '/' + a_data[1] + '/' + a_data[2] + ' ' + a_data[3] + ':' + a_data[4] + '</span> <span class="title"><a href="' + indirizzo + '">' + titolo + '</a></span></div><div class="line2"><span class="description">' + testo + '</span></div></div>';
				$('#diweb-feed-inner').append( html );
			});
		} else {
			$('#diweb-feed-inner').append('<div><p style="text-align: left; padding: 5px 10px;">Servizio momentaneamente non disponibile</p></div>');
		};
		$('div.description').jTruncate({  
			length: 400,  
			minTrail: 50,
			moreText: "[Leggi tutto]",
			lessText: "[Riduci]",
			ellipsisText: "...",
			moreAni: "fast",
			lessAni: "fast"
		}); 
		$('#feed-diweb').show();
	});
};

/*
 * Funzione che genera il box con il video di youtube a partire da un link
 * I parametri di input sono:
 * width = larghezza widget in px (altezza automatica),
 * youtube_box = id box di destinazione che conterrà la gallery, viene generato dinamicamente
 * youtube_txt = id box con testo descrittivo (preesistente)
 * youtube_link = id box con link (preesistente)
 */
var isYoutubeVideoLink = new RegExp ('^(http:\\/\\/www\\.youtube\\.com\\/watch){1}(\\?v=|#!v=){1}[a-zA-Z0-9-_]{11}$'); // L'ID del video è formato da 11 caratteri tra lettere, numeri e -
function youtubeBox ( width, youtube_box, youtube_txt, youtube_link ) {
    // si suppone che il link sia inserito nella forma "http://www.youtube.com/watch?v=0eUaPcXsPsA"
    // quindi effettuo un controllo sul fatto che il link si ben formato
    var videoLink = $.trim($('#' + youtube_link).text());
    var height = Math.round( width / 1.245 );
    // se il contenuto di videoLink non è vuoto e se sembra contenere un link a youtube, creo il box video
    if ( isYoutubeVideoLink.test( videoLink ) ) {
        var array_videoLink = videoLink.split ('=');
        // l'array così creato sarà del tipo: ['http://www.youtube.com/watch?v:','0eUaPcXsPsA']
        var videoID = array_videoLink[ array_videoLink.length - 1 ]; // l'ultima posizione nell'array contiene l'ID del video
        var videoDescription = $.trim( $('#' + youtube_txt).text() );
        // Controllo che la descrizione inserita non sia vuota, nel qual caso inserisco un testo alternativo
        if ( videoDescription ) {
            var didascaliaY = videoDescription;
        } else {
            var didascaliaY = 'Guarda su Youtube';
        };

        // Nascondo la cella con la descrizione e svuoto il contenuto della cella con il link che sostituisco con il video
        $('#' + youtube_link).attr('class','youtube-box').attr('id',youtube_box).html('<div id="' + youtube_box + '-inner" class="youtube-box-inner"><div id="youtube-container" class="container"><div class="zoom-button youtube-button" style="cursor: pointer" title="Clicca qui per ingrandire il video">Clicca qui per ingrandire</div><div class="swfObject" style="float:left; width:' + width + 'px; height:' + height + 'px;"><object width="' + width + '" height="' + height + '"><param name="movie" value="http://www.youtube.com/v/' + videoID +'&hl=it_IT&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + videoID + '&hl=it_IT&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + width + '" height="' + height + '"></embed></object></div><div class="descrizione"><a href="' + videoLink + '" target="_blanck" title="Clicca qui per visualizzare il video su youtube">' + didascaliaY + '</a></div></div><div id="dialogContent-' + youtube_box + '"></div></div>');
        $('#' + youtube_txt).hide();

        // Parametri dialog per l'opzione di ingrandimento della gallery di youtube
        var dialogOptionsY = {
            width: 600,
            height: 490,
            autoOpen: false,
            resizable: true,
            closeOnEscape: false,
            dialogClass: 'youtube-dialog',
            modal: true,
            buttons: { "Chiudi": function() { $(this).dialog("close"); } },
            open: function () {
                // Creo il contenuto del dialog
                    $('#dialogContent-' + youtube_box).empty();
                    $('<div class="swfObject"><object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/' + videoID + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed wmode="transparent" src="http://www.youtube.com/v/' + videoID + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object></div><div class="link"><a href="' + videoLink + '" title="Link al video">' + videoLink + '</a></div>').appendTo('#dialogContent-' + youtube_box);
                var dialog_title = '<a href="' + videoLink + '" title="Clicca qui per visualizzare il video su youtube" target="_blanck">' + didascaliaY + '</a>';
                $('#dialogContent-' + youtube_box).dialog( 'option', 'title', dialog_title );
            },
            close: function () {
                $('object, embed').css('visibility','visible');
                $('#dialogContent-' + youtube_box).empty();
            }
        };

        // Creo il dialog
        $('#dialogContent-' + youtube_box).dialog(dialogOptionsY);

        // Pulsante per apertura dialog
        $('#' + youtube_box + ' .youtube-button').click( function(e) {
            $('object, embed').css('visibility','hidden');
            $('#dialogContent-' + youtube_box).dialog('open');
            e.preventDefault();
        });
    } else { // se videoLink non sembra essere nella forma corretta, mostro um messaggio di errore
        $('#' + youtube_link).attr('class','youtube-box').attr('id',youtube_box).html('<div id="' + youtube_box + '-inner" class="box-inner"><div class="youtube box-title"><span>Youtube</span></div><div class="container" id="youtube-container"><div class="error"><p>Controlla il link al video di Youtube che hai inserito in quanto non sembra essere corretto.</p><p><a href="' + videoLink + '">' + videoLink + '</a></p></div></div></div>');
        $('#' + youtube_txt).hide();
    }; // chiusura if video Youtube
}; // chiusura funzione youtubeBox


// ###################
// OPERAZIONI SUL DOM
// ###################

$(document).ready( function () {

	$('#feed-diweb').hide();
	var feed_url = $('#feed-diweb a').attr('href');
	diwebFeedWidget ( feed_url, '4', '#feed-diweb', 'Abbonati al feed' );
  // controllo prima se è presente un link al video di youtube e quindi creo il box
	if ($.trim($('#youtube-link-1').text())) {
    youtubeBox ( 240, 'yt-box-1', 'youtube-txt-1', 'youtube-link-1' );
	};
	if ($.trim($('#youtube-link-2').text())) {
    youtubeBox ( 240, 'yt-box-2', 'youtube-txt-2', 'youtube-link-2' );
	};
	$('#feed-diweb p').remove();
});
