CommentiConf.prototype = {
  reloadElements  : function() {
    new AdvObject(['adv7','adv1','manchette','advSkinIframe']).reloadADV();
    new AdvObject(['adv7','adv1','manchette','advSkinIframe']).reloadGA();
  },
  pageDesc  : function() {
    return $("meta[name='description']").attr("content");
  },
  pageImg  : function() {
    var img = 'http://images.virgilio.it/VIRGILIO/header2008/logo_v.gif';
    if ($("link[rel='image_src']").length > 0 ) {
      img = $("link[rel='image_src']").eq(0).attr("href");
    } else if ($('.su_immagine img').length > 0) {
      img = $('.su_immagine img').eq(0).attr('src');
    }
    return img;
  },
	getOffset : function() {
		var cid = '';
		if ($('#commenti .commento').length > 0 ) {
			cid = $('#commenti .commento:last').attr('cid');
		}
		return cid;
	},
	pageCommUrl : function(cid) {
	  if (this.pageUrl.indexOf('/commenti') > 0 || this.category == 'video' || this.category == 'eventi' || this.category == 'aziende') {
	    return this.pageUrl;
	  } else {
  	  var commUrl = this.host + '/commenti' + this.uri;
  	  //var commUrl = this.host + '/common/tech_includes/commenti2010/commento.html';
  	  commUrl = commUrl.substr(0,commUrl.length-5) + '/commento__' + this.pid + '__' + cid + '.html';
		  return commUrl;
  	}
	},
	serverCall : function() {
		//console.log("case: " +this.ajaxFunctionType);
	 switch (this.ajaxFunctionType) {
    case 0:
      this.ajaxLabel = 'Commentario List';
      this.commentoSort = 'time';
    	this.ajaxUrl = '/tech-commenti/rst/commentarioMostRecent/'+this.pname+'/'+this.pid;
    	this.ajaxParams = '';
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
  		  //$("#commenti").css('display','none');
		    $('#commenti').html($('#commenti_temp').html());
		  this.setHtmlComment();
        //$("#commenti").css('display','block').slideDown(500);//Versione alternativa: .css('display','block');
    	}
    	this.ajaxCall();
    break;
    case 1:
      this.ajaxLabel = 'Commento Get';
      this.ajaxUrl = '/tech-commenti/rst/commentoGetWithoutParams/'+this.pname+'/'+this.pid+'/'+this.cid;
      this.ajaxParams = {"dirisp":this.rispostaSortDir};
      this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
		    $('#commenti_temp #risp_' + CC.cid).css('display','none');
        $('#commenti #risp_' + CC.cid).slideUp(200);  // nascondo le risposte
        var t = $('#commenti_temp .risposte').clone();
        setTimeout(function(){
          $('#commenti #risp_' + CC.cid).html(t.html());
    			$('#commenti #risp_' + CC.cid).slideDown(500);  // mostro le risposte
  			}, 200);
		  }
		  /*
    	this.ajaxCallBack = function(r) {
		    //$('#commenti_temp .risposte').css('display','none');
        //$('#commenti #risp_' + CC.cid).slideUp(200);  // nascondo le risposte
        //var t = $('#commenti_temp .risposte').clone();
        //setTimeout(function(){
          $('#commenti_temp .risposte').css('display','none');
          //$('#commenti_temp .risposte').slideDown(500);  // mostro le risposte
          $('#commenti #risp_' + CC.cid).html($('#commenti_temp .risposte').html());
          //$('#commenti #risp_' + CC.cid).css('display','none');
    			$('#commenti #risp_' + CC.cid).slideDown(500);  // mostro le risposte
  			//}, 200);
		  }
		  */
    	this.ajaxCall();
    	this.reloadElements();
      break;
    case 2:
	    var txt = this.activeNode.parent().find('TEXTAREA').val();
      if ( checkText(txt) && checkVote() ) {
        //this.testo = txt.replace(/\n/g, "<br />");
        this.testo = txt;
        this.ajaxLabel = 'Pubblica Commento';
        var cont = eval($('#commenti .comm_number').attr("count")); // ricavo il numero dei commenti
      	var commStatus = $('#label_commentario').attr('status'); // ricavo il numero dei commenti
      	this.ajaxParams = {"pname":this.pname,"pid":this.pid,"nick":LV.nickname,"auth":LV.authType,"body":this.testo};
      	if (this.ppayload != null) { $.extend(this.ajaxParams,{"ppayload":this.ppayload}); };
      	if (Number(commStatus)>0) {
      		this.commLabel = eval(cont + 1) + ' commenti';
      		this.ajaxUrl = '/tech-commenti/rst/commentoAdd';
      	} else {
      		this.commLabel = '1 commento';
      		this.ajaxUrl = '/tech-commenti/rst/commentoEnhancedAdd';
      		$.extend(this.ajaxParams,{"ptitle":this.ptitle,"url":this.pageUrl,"tpl":this.tpl,"lbl":this.label})
      	}
      	this.ajaxType = 'POST';
      	this.ajaxCallBack = function(r) {
          // Profilo utente loggato
          this.setHtmlLoggedUser();
			$("#commenti_temp .commento").prepend($('<p/>').html(this.testo.replace(/\n/g, "<br />"))); // Aggiungo il testo
    	    $("#commenti_temp .comm_tools").after(this.setHtmlAuthor()); // Aggiungo l'html dell'autore
          $("#commenti_temp .rispondi").css('display','none');
    			var n = $('#commenti_temp').html();
    			$(n).insertAfter($('#commenti .comm_number'));
    			// Chiamata a facebook
    			this.faceBookCall($('#commenti_temp .commento').attr('cid'));
    			// Chiamata al recommender
    			if (CC.REC) {
      			CC.REC.trackItemRequest('',CC.recId,'comment');
      			if ( checkVote() && CC.voting == 'true' ) {
      			  CC.REC.voteItemRequest(CC.category,CC.recId,$('#curr_stars').attr('vote'),CC.istat,CC.from,true);
      			}
      		}
     			$('#commenti_temp').remove();
    			this.setHtmlAuthor;
    			$('.comm_number span').html(this.commLabel); // sostituisco il valore con il numero del commento appena aggiunto
    			$('#commenti .comm_number').attr("count",Number($('#commenti .comm_number').attr("count"))+1);
    			if ( Number($('#label_commentario').attr('status')) < 0 ) {$('#label_commentario').attr('status','1'); };
    			$('#commenti .commento:first').slideDown(500); // mostro il commento appeso
    			$('#commenti .rispondi:first').slideDown(500); // mostro la barra del rispondi
    			$('#comm_txt').attr("value","Scrivi il tuo commento").css('height','32px'); // Reimposto la textarea
    			$('#testo_falso').remove();
          if ($('#curr_stars')) {
            // Spegimento pulsante Pubblica
        		$('span.pubblica_comm').css({'display':'block'});
        		$('a.pubblica_comm').css({'display':'none'});
        		// Rimozione Voto
            $('#curr_stars').remove();
          }
      	}
      	this.ajaxCall();
      	this.reloadElements();
      }
      break;
    case 3:
      var txt = this.activeNode.parent().find('TEXTAREA').val();
	    //this.testo = txt.replace(/\n/g, "<br />");
        this.testo = txt;
      if ( checkText(txt)) {
        this.ajaxLabel = 'Pubblica Risposta';
      	var cid = $(this.activeNode).attr('cid');
      	this.ajaxUrl = '/tech-commenti/rst/rispostaAdd';
      	this.ajaxParams = {"pname":this.pname,"pid":this.pid,"cid":cid,"nick":LV.nickname,"auth":LV.authType,"body":this.testo};
      	if (this.ppayload != null) { $.extend(this.ajaxParams,{"ppayload":this.ppayload}); };
        this.ajaxType = 'POST';
      	this.ajaxCallBack = function(r) {
          // Profilo utente loggato
          this.setHtmlLoggedUser();
    	    $("#commenti_temp .risposta").prepend($('<p/>').html(this.testo.replace(/\n/g, "<br />"))); // Aggiungo il testo
    	    $("#commenti_temp .comm_tools").after(this.setHtmlAuthor()); // Aggiungo l'html dell'autore

  				var risp_pres = $('#risp_'+cid+' .risposta').length;
  				var n = $('#commenti_temp').html();

          $('#risp_'+cid).attr('count',eval($('#risp_'+cid+' .risposta').length+1));
  				if(risp_pres == 0){
  					$('#risp_'+cid).html($(n)); // Nessuna risposta
  				}else{
  					$('#risp_'+cid).append($(n)); // Risposte presenti
  				}

    			//Mostro la risposta
    			$('#commenti #risp_'+ cid + ' .risposta:last').slideDown(500); // mostro la risposta appesa
    			$('.risp_txt').attr("value","Scrivi la tua risposta").css('height','15px'); // Reimposto la textarea
          $('#testo_falso').remove();
		    }
		    this.ajaxCall();
		    this.reloadElements();
      }
      break;
    case 4:
      this.ajaxLabel = 'Commento Piace';
    	var cid = $(this.activeNode).closest('.commento').attr("cid");
    	this.ajaxUrl = '/tech-commenti/rst/commentoLike';
    	this.ajaxParams = {"pname":this.pname,"pid":this.pid,"cid":cid,"nick":LV.nickname,"auth":LV.authType};
      this.ajaxType = 'POST';
    	this.ajaxCallBack = function(r) {
        // Profilo utente loggato
        this.setHtmlLoggedUser();
  			$(this.activeNode).fadeTo("slow", 0.33).addClass('off').removeAttr('title');
  			$(this.activeNode).closest('.comm_tools').children().children('.comm_npiac').fadeTo("slow", 0.33).addClass('off').removeAttr('title');
  			$('.tool_tip').remove();
  			if (r == 0) {
  			  createErrorMessage('ATTENZIONE:<br> Hai gi&agrave; votato questo commento');
  			} else {
  			  $(this.activeNode).html($('<span/>').html(Number($(this.activeNode).children().html())+1));
  			};
    	}
    	this.ajaxCall();
    	this.reloadElements();
      break;
    case 5:
      this.ajaxLabel = 'Commento Non Piace';
    	var cid = $(this.activeNode).closest('.commento').attr("cid");
    	this.ajaxUrl = '/tech-commenti/rst/commentoDislike';
    	this.ajaxParams = {"pname":this.pname,"pid":this.pid,"cid":cid,"nick":LV.nickname,"auth":LV.authType};
      this.ajaxType = 'POST';
    	this.ajaxCallBack = function(r) {
        // Profilo utente loggato
        this.setHtmlLoggedUser();
  			$(this.activeNode).fadeTo("slow", 0.33).addClass('off').removeAttr('title');
  			$(this.activeNode).closest('.comm_tools').children().children('.comm_piac').fadeTo("slow", 0.33).addClass('off').removeAttr('title');
  			$('.tool_tip').remove();
  			if (r == 0) {
  			  createErrorMessage('ATTENZIONE:<br> Hai gi&agrave; votato questo commento');
  			} else {
  			  $(this.activeNode).html($('<span/>').html(Number($(this.activeNode).children().html())+1));
  			};
    	}
    	this.ajaxCall();
    	this.reloadElements();
      break;
    case 6:
      this.ajaxLabel = 'Commentario List - Piu votati';
      this.commentoSort = 'vote';
    	this.ajaxUrl = '/tech-commenti/rst/commentarioMostVoted/'+this.pname+'/'+this.pid;
    	this.ajaxParams = '';
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
			  $("#commenti").css('display','none');
        $('#commenti').html($('#commenti_temp').html());
        this.setHtmlComment();
        $("#commenti").slideDown(500);//Versione alternativa: .css('display','block');
    	}
    	this.ajaxCall();
    	this.reloadElements();
      break;
    case 7:
      this.ajaxLabel = 'Commentario List - Piu discussi';
      this.commentoSort = 'pop';
    	this.ajaxUrl = '/tech-commenti/rst/commentarioMostAnswered/'+this.pname+'/'+this.pid;
    	this.ajaxParams = '';
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
			  $("#commenti").css('display','none');
        $('#commenti').html($('#commenti_temp').html());
        this.setHtmlComment();
        $("#commenti").slideDown(500);//Versione alternativa: .css('display','block');
    	}
    	this.ajaxCall();
    	this.reloadElements();
      break;
    case 8:
      this.ajaxLabel = 'Commentario List - Offset';
    	this.ajaxUrl = '/tech-commenti/rst/commentarioMostRecent/'+this.pname+'/'+this.pid;
    	//console.log('Offset: ' + this.getOffset());
    	this.ajaxParams = {"offset":this.getOffset};
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
        if ( $('.show_comm').length > 0 ) { // Aggiunta blocco di commenti
				  $("#commenti_temp .commento").css('display','none');
				  $("#commenti_temp .rispondi").css('display','none');
				  $('#commenti .show_comm').before($('#commenti_temp').html())
					$('#commenti .commento').slideDown(500);  // mostro i commenti
					$('#commenti .rispondi').slideDown(500);  // e le form per rispondere
					this.setHtmlOffset();
				}
    	}
    	this.ajaxCall();
    	this.reloadElements();
      break;
    case 9:
	  createSpoilerMessage('Il termine spoiler &egrave; spesso usato in ambito cinematografico come segnalazione quando il testo riporta delle informazioni che potrebbero svelare i punti salienti della trama del film. Sei sicuro che questo commento riporti degli spoiler?',0);
      break;
   }
   return false;
  },
  faceBookCall : function(cid) {
    ajaxLabel = 'Pubblica su FaceBook';
    if ( LV.connectFB ) {
			// Chiamata per BI
			vBI.trackBiImage('posid','CONTEXT=virgilio&ACTION=NAV&POSID=1050&CONTENT=comm_publica_fb');
      var fbPostUrl = 'http://aaacsc.virgilio.it/RPFB/postComment.do?';
      var params = 'message='+fixedEncodeURIComponent(this.testo.replace(/<\/?[^>]+(>|$)/gi,' '))+'&link='+fixedEncodeURIComponent(this.pageCommUrl(cid)+'?shrbox=facebook_comm')+'&picture='+fixedEncodeURIComponent(this.pageImg())+'&name='+fixedEncodeURIComponent(this.ptitle)+'&caption='+fixedEncodeURIComponent(this.pageCommUrl(cid))+'&description='+fixedEncodeURIComponent(this.pageDesc())+"&callback=?";
      //console.log('fb post url '+fbPostUrl+params);
      $.getJSON(fbPostUrl+params, function(data) {
        //console.log('POSTATO SU FB!! ');
      });
    }
  	return false;
  },
  // PATCH **LOCAL** PER CHIAMATA AJAX
  ajaxCall : function() {
  	//console.log("URL: " + this.ajaxUrl + " - PARAMS: " + this.ajaxParams);

  	var temp = this;
  setTimeout(function(){
	  $.ajax({
			url: temp.ajaxUrl,
			data: temp.ajaxParams,
			dataType: 'html',
			type: temp.ajaxType,
			timeout: 10000,
			cache: false,
			error: function(jqXHR, textStatus, errorThrown){ createErrorMessage('ATTENZIONE:<br> ',textStatus); },
			success:	function(r){
			  //console.log(r);
				if (checkServerResponse(r)) {
					createTemp(r);
					temp.ajaxCallBack(r);
					$('#commenti_temp').remove();
				} else {

					if (temp.ajaxType=="GET"){
						$("#commenti").html(r.replace("layerError", "layerErrorInternal"));
						$("#commenti .layerErrorInternal p").html("Attenzione! Il servizio commenti non &egrave; al momento disponibile.");
						}
					else
						manageError(r);

				}
		  }
		});
	}, 100);

  	return false;
  },
  toolLink : function(typ,node) {
   console.log("Tipo: " + typ + ' - cid: ' + $(node).parents('.commento').attr("cid"));
   var label = 'Tool';
	 switch (Number(typ)) {
    case 0:
      label = 'Click su pulsante Facebook';
      vBI.trackBiImage('posid','CONTEXT=virgilio&ACTION=NAV&POSID=1050&CONTENT=comm_facebook','http://www.facebook.com/sharer.php', function() {} );
      window.open('http://www.facebook.com/sharer.php?u=' + fixedEncodeURIComponent(this.pageCommUrl($(node).parents('.commento').attr("cid"))+'?shrbox=facebook_comm'),'','menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes,width=1000,height=400');
      this.reloadElements();
    break;
    case 1:
      label = 'Click su pulsante Twitter';
      vBI.trackBiImage('posid','CONTEXT=virgilio&ACTION=NAV&POSID=1050&CONTENT=comm_twitter','http://twitter.com/intent/tweet', function() {} );
      window.open('http://twitter.com/intent/tweet?text=' + fixedEncodeURIComponent(truncateText($(node).parents('.commento').children("p"),140)) + '&url=' + fixedEncodeURIComponent(this.pageCommUrl($(node).parents('.commento').attr("cid"))+'?shrbox=twitter_comm'),'','menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes,width=1000,height=400');
      this.reloadElements();
    break;
    case 2:
      label = 'Click su pulsante Permalink';
      var tree = $(node).parent().parent().next('.comm_aut');
    	var prlnkId = $('.prlnk').length;
    	var lnk = this.pageCommUrl($(node).parents('.commento').attr("cid"));
    	var selElm = $(node).parent().parent().parent().children(".prlnk");
    	if(selElm.css("display")=="block"){
    		selElm.slideUp(500);
    	} else {
    	  if ($('.prlnk').length > 0){
      		$('.prlnk').slideUp(500);
      	}
      	var inside = '<span></span><input type="text" value="'+lnk+'"/>';
      	tree.after('<div class="prlnk" id="prlnk' + prlnkId + '">'+inside+'</div>');
      	$('#prlnk' + prlnkId).slideDown(600, function(){$('#prlnk' + prlnkId +' INPUT').focus().select();});
      }
      this.reloadElements();
    break;
    case 3:
      this.ajaxLabel = 'Click su pulsante Segnala un abuso della Risposta';
    	this.ajaxUrl = '/tech-commenti/rst/rispostaSegnalaAbuso/'+this.pname+'/'+this.pid+'/'+$(node).parents('.commento').attr("cid")+'/'+$(node).attr("rid");
    	this.ajaxParams = '';
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
  			if (r == 'OK') {
         $('.layerError P').html('La tua segnalazione &egrave; andata a buon fine. Grazie');
         $('.layerError .confirm').remove();
  			};
    	  setTimeout(function() {
      	  $('.layerError').css({'display':'none'});
      	  $('.overlay').css({'display':'none'});
    		}, 5000);
    	}
    	this.ajaxCall();
      //window.open('http://abusi.community.virgilio.it/?serv=Commenti&referrer=' + this.pageCommUrl($(node).parents('.commento').attr("cid")),'');
      this.reloadElements();
    break;
    case 4:
      this.ajaxLabel = 'Click su pulsante Segnala un abuso del Commento';
    	this.ajaxUrl = '/tech-commenti/rst/commentoSegnalaAbuso/'+this.pname+'/'+this.pid+'/'+$(node).parents('.commento').attr("cid");
    	this.ajaxParams = '';
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
  			if (r == 'OK') {
         $('.layerError P').html('La tua segnalazione &egrave; andata a buon fine. Grazie');
         $('.layerError .confirm').remove();
  			};
    	  setTimeout(function() {
      	  $('.layerError').css({'display':'none'});
      	  $('.overlay').css({'display':'none'});
    		}, 5000);
    	}
    	this.ajaxCall();
      //window.open('http://abusi.community.virgilio.it/?serv=Commenti&referrer=' + this.pageCommUrl($(node).parents('.commento').attr("cid")),'');
      this.reloadElements();
    break;
    case 5:
      this.ajaxLabel = 'Click su pulsante Segnala un abuso del Commento';
    	this.ajaxUrl = '/tech-commenti/rst/commentoSegnalaAbuso/'+this.pname+'/'+this.pid+'/'+$(node).parents('.commento').attr("cid");
    	this.ajaxParams = '';
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
  			if (r == 'OK') {
         $('.layerError P').html('La tua segnalazione &egrave; andata a buon fine. Grazie');
         $('.layerError .confirm').remove();
  			};
    	  setTimeout(function() {
      	  $('.layerError').css({'display':'none'});
      	  $('.overlay').css({'display':'none'});
    		}, 5000);
    	}
    	this.ajaxCall();
      //window.open('http://abusi.community.virgilio.it/?serv=Commenti&referrer=' + this.pageCommUrl($(node).parents('.commento').attr("cid")),'');
      this.reloadElements();
    break;
    case 9:
      this.ajaxLabel = 'Click su pulsante Segnala uno spoiler';
    	this.ajaxUrl = '/tech-commenti/rst/commentoSegnalaSpoiler/'+this.pname+'/'+this.pid+'/'+$(node).parents('.commento').attr("cid");
    	this.ajaxParams = '';
    	this.ajaxType = 'GET';
    	this.ajaxCallBack = function(r) {
  			if (r == '1') {
         $('.layerError P').html('La tua segnalazione &egrave; andata a buon fine. Grazie');
         $('.layerError .confirm').remove();
  			};
    	  setTimeout(function() {
      	  $('.layerError').css({'display':'none'});
      	  $('.overlay').css({'display':'none'});
    		}, 5000);
    	}
    	this.ajaxCall();
      this.reloadElements();
    break;
   }
   //console.log(label);
   return false;
  },

  setHtmlAuthor : function() {
    // Html del nick
    var d = user_date();
    var risp_aut = $('<div></div>').addClass('comm_aut')
  		.append($('<span></span>').addClass('bll'))
  		.append($('<a></a>').attr({'href':'http://people.virgilio.it/profilo/'+LV.nickname,'title':LV.nickname})
  		  .append($('<img></img>').attr({'src':'http://multimedia.community.virgilio.it/contenuti/'+LV.nickname+',c00.jpg','alt':LV.nickname}))
  		  .append($('<span></span>').html('da: '))
  		  .append(LV.nickname)
  		)
  		.append($('<span></span>').addClass('date').html(d));
  	return risp_aut;
  },
  setHtmlLoggedUser : function() {
    // Profilo utente loggato
  	if (LV.logged && $('#label_commentario').length > 0 && $('.user_comm').text() == '') {
  		$('.user_comm').html(
    		$('<a></a>')
    	  .attr({'href':'http://people.virgilio.it/profilo/'+LV.nickname,'title':LV.nickname})
    		.append($('<img></img>').attr({'src':'http://multimedia.community.virgilio.it/contenuti/'+LV.nickname+',c00.jpg','alt':LV.nickname}))
    		.append(LV.nickname)
  		);
  	};
  },
  setHtmlComment : function() {
	  // Settaggio del commentario
    if (this.label != '(none)' && this.label !== '' ) {
      $('#label_commentario').html($('<span></span>')).append(this.label);
    }

	  // Stelline per votazione
    if (this.voting == 'true') {
      var n = $('<div></div>').addClass('rating_whi_comm')
	  	.append($('<span></span>').html('Clicca qui per votare'))
  		.append($('<ul></ul>').addClass('star-rating').attr({'id':'ul-stars'})
    		.append($('<li></li>').append($('<a></a>').addClass('one-star').attr({'title':'scarso'}).html('1')))
    		.append($('<li></li>').append($('<a></a>').addClass('two-star').attr({'title':'mediocre'}).html('2')))
    		.append($('<li></li>').append($('<a></a>').addClass('three-star').attr({'title':'sufficiente'}).html('3')))
    		.append($('<li></li>').append($('<a></a>').addClass('four-star').attr({'title':'buono'}).html('4')))
    		.append($('<li></li>').append($('<a></a>').addClass('five-star').attr({'title':'ottimo'}).html('5')))
  		)
  		$(n).insertAfter($('#comm_insert .comm_txt'));
    }

    // Profilo utente loggato
    this.setHtmlLoggedUser();

    // Linkeria per ordinamento
    if ($('.comm_number').attr("count") > 10) {
    	var comm_order = $('<dl></dl>').addClass('comm_order').append($('<dt></dt>').html('Mostra i commenti'));
    	var order_time = $('<dd></dd>');
    	if (CC.commentoSort!='time') {
    		order_time.append($('<a></a>').addClass('sort_time').attr({'href':'#','title':'Pi&ugrave; recenti'}).html('Pi&ugrave; recenti'));
    	} else {
    		order_time.html('Pi&ugrave; recenti');
    	}

    	var order_vot = $('<dd></dd>').addClass('center');
    	if (CC.commentoSort!='vote') {
    		order_vot.append($('<a></a>').addClass('sort_vote').attr({'href':'#','title':'Pi&ugrave; votati'}).html('Pi&ugrave; votati'));
    	} else {
    		order_vot.html('Pi&ugrave; votati');
    	}

    	var order_pop = $('<dd></dd>');
    	if (CC.commentoSort!='pop') {
    		order_pop.append($('<a></a>').addClass('sort_pop').attr({'href':'#','title':'Pi&ugrave; discussi'}).html('Pi&ugrave; discussi'));
    	} else {
    		order_pop.html('Pi&ugrave; discussi');
    	}

    	comm_order.append(order_time).append(order_vot).append(order_pop);
    	if ($('.comm_order').length > 0 ) {
    	  $('.comm_order').remove();
    	}
    	$('.comm_number').append(comm_order);
    }
    this.setHtmlOffset();
	return false;
  },

  setHtmlOffset : function() {
    // Gestione offset commenti
    if (CC.commentoSort=='time') {
    	if ($('#commenti .commento').length > 0 && ($('#commenti .comm_number').attr("count") > $('#commenti .commento').length) && $('.show_comm').length == 0) {
    	  var lastNode = $('#commenti .commento:last').next();
    	  if (lastNode.length == 0) {
    	    lastNode = $('#commenti .commento:last');
    	  }
    	  lastNode.after($('<div></div>').addClass('show_comm').html('Vedi altri commenti'));
    	} else if ( $('#commenti .commento').length > 0 && ($('#commenti .comm_number').attr("count") <= $('#commenti .commento').length) ) {
    	  $('.show_comm').remove();
    	}
    }
    return false;
  }

}

/* INIZIALIZZAZIONE OGGETTO DI CONFIGURAZIONE COMMENTI */
var CC = new CommentiConf();

//-------------------------------------------------------------------------------------------------------
//	I N I Z I O   F U N Z I O N I    A L   C L I C K  - L I V E
//-------------------------------------------------------------------------------------------------------

// Funzionamento del click sul pulsante 'Pubblica' (un commento)
$("#commenti a.pubblica_comm").live("click", function(){checkLogin(2,$(this)); return false;});

// Funzionamento del click sul pulsante 'Rispondi' (ad un commento)
$("#commenti a.pubblica_risp").live("click", function(){checkLogin(3,$(this)); return false;});

// Funzionamento del click sul pulsante 'Mi piace'
$("#commenti .comm_piac").live("click", function(){if (!$(this).hasClass('off')) {checkLogin(4,$(this));return false;} return false;});

// Funzionamento del click sul pulsante 'Non mi piace'
$("#commenti .comm_npiac").live("click", function(){if (!$(this).hasClass('off')) {checkLogin(5,$(this));return false;} return false;});

// Gestione del pulsante 'Facebook'
$("#commenti .comm_fcb").live("click", function(){CC.toolLink(0,$(this));return false;});

// Gestione del pulsante 'Twitter'
$("#commenti .comm_tw").live("click", function(){CC.toolLink(1,$(this));return false;});

// Gestione del pulsante "Permalink"
$("#commenti .comm_prlnk").live("click", function(){CC.toolLink(2,$(this));return false;});

// Gestione del pulsante 'Segnala un abuso' sulla risposta
$("#commenti .risposte .comm_sgn").live("click", function(){CC.activeNode=$(this);createAbuseMessage('Vuoi davvero segnalare questa risposta come inadatta?',3);return false;});

// Gestione del pulsante 'Segnala un abuso' sul commento
$("#commenti .comm_sgn").live("click", function(){CC.activeNode=$(this);createAbuseMessage('Vuoi davvero segnalare questo commento come inadatto?',4);return false;});

// Gestione del pulsante 'Segnala spoiler' sul commento
$("#commenti .comm_spoiler").live("click", function(){CC.activeNode=$(this); checkLogin(9,$(this)); return false;});

// Gestione del pulsante 'Segnala' nella finestra di segnalazione abuso
$("#abuseConfirm").live("click", function(){CC.toolLink($(this).attr('pos'),CC.activeNode);return false;});

// Gestione del pulsante 'Segnala' nella finestra di segnalazione spoiler (per Virgilio Film)
$("#spoilerConfirm").live("click", function(){CC.toolLink(9,CC.activeNode);return false;});

// Gestione click 'Leggi tutte le risposte'
$('#commenti .show_risp').live("click", function(){CC.cid = $(this).parent().parent('.commento').attr('cid');CC.ajaxFunctionType=1;CC.serverCall();return false;});

// Gestione click 'Piu' recenti'
$('#commenti .sort_time').live("click", function(){CC.ajaxFunctionType=0;CC.serverCall();return false;});

// Gestione click 'Piu' votati'
$('#commenti .sort_vote').live("click", function(){CC.ajaxFunctionType=6;CC.serverCall();return false;});

// Gestione click 'Piu' discussi'
$('#commenti .sort_pop').live("click", function(){CC.ajaxFunctionType=7;CC.serverCall();return false;});

// Gestione click 'Vedi altri commenti'
$('#commenti .show_comm').live("click", function(){CC.ajaxFunctionType=8;CC.serverCall();return false;});

//Gestione espansione barra risposte
$('#commenti .rispondi').live('mouseover mouseout click', function(event) {
  if (event.type == 'mouseover') {
    $(this).css("color","#c3c3c3");
  } else if (event.type == 'click')  {
    $(this).addClass('on');
	$(this).unbind("click");
  }else {
	$(this).css("color","#000000");
  }
})

//Gestione mouseover su show commenti e show risposte
$('#commenti .show_comm , #commenti .show_risp').live("mouseenter",function(){$(this).addClass('on')}).live("mouseout",function(){$(this).removeClass('on')})


// Gestione del 'Vedi tutto il testo'
$('.add').live('click',function(){
  if ($(this).parents('.risposte')) {
    $(this).parent().animate({'height':$(this).attr('h')},500);
    var f_height = ($(this).attr('h'))-($(this).parent().outerHeight())+14;
    $(this).parents('.risposte').animate({'height':'+='+f_height+'px'},500);
  } else {
    $(this).parent().animate({'height':$(this).attr('h')},500);
  }
  $(this).remove();
});

// Gestione Textarea
$("#commenti TEXTAREA").live("focus",function(){
	// Funzione di abilitazione bottone pubblica
		if($(this).hasClass('risp_txt')){
		   var selec = $(this).parent().attr('id');
			$('#'+selec+' span.pubblica_risp').css({'display':'none'})
			$('#'+selec+' a.pubblica_risp').fadeIn(500);
			//console.log(selec);
		}
		else if($(this).hasClass('comm_txt')){
			$('span.pubblica_comm').css({'display':'none'})
			$('a.pubblica_comm').fadeIn(500);
		}
		// Fine funzione di abilitazione bottone pubblica
	$(this).autoResize({
	// On resize:
	onResize : function() {
		$(this).css({opacity:0.8});
	},
	// After resize:
	animateCallback : function() {
		$(this).css({opacity:1});
	},
	// Quite slow animation:
	animateDuration : 200,
	// More extra space:
	extraSpace : 20
	});
}).live('blur',function(){
  	if($(this).hasClass('risp_txt')){ // Risposte
		  var selec = $(this).parent().attr('id');
  	  setTimeout(function() {
    		$('#'+selec+' span.pubblica_risp').css({'display':'block'});
    		$('#'+selec+' a.pubblica_risp').css({'display':'none'});
    		$('#testo_falso').remove();
  		}, 400);
		} else {  // Commento
  	  setTimeout(function() {
  		if (CC.voting != 'true') {
    		$('span.pubblica_comm').css({'display':'block'});
    		$('a.pubblica_comm').css({'display':'none'});
    	}
  		$('#testo_falso').remove();
  		}, 400);
  	}
})

// Gestione del ToolTip
$(".comm_tools A").live('mouseover mouseout', function(event) {
  if ( !$(this).is('.off') ) {
    if (event.type == 'mouseover') {
		var titolo = $(this).attr("title");
		if(titolo != ''){
			$(this).attr('rel',titolo);
			$(this).attr("title","");
		}else {
			titolo = $(this).attr("rel");
		}
		position = $(this).offset();
  		tooltip = $("<span></span>").appendTo("BODY").addClass("tool_tip").html(titolo);
  		$("<span/>").appendTo($('.tool_tip')).css('left',($('.tool_tip').width()/2)+2)
  		cont_position = ($('.tool_tip').width()/2)-($(this).outerWidth()/2)
  		tooltip.css({"left":((position.left-cont_position)-10),"top":(position.top+30),"z-index":"14"})
	} else {
      	$('.tool_tip').remove();
    }
  }
});

// Gestione delle stelline per la votazione **LOCAL**
$('#ul-stars li a').live("click", function(){
    var voteStr = '';
    var testo = $(this).html();
  	switch (Number(testo)) {
      case 1: voteStr = 'ratePoor'; break;
      case 2: voteStr = 'rateMediumPoor'; break;
      case 3: voteStr = 'rateAverage'; break;
      case 4: voteStr = 'rateGood'; break;
      case 5: voteStr = 'rateExcellent'; break;
    }
	  if ($('#curr_stars')) {
      $('#curr_stars').remove();
    }
    $('#ul-stars').append( $('<li></li>').attr({'id':'curr_stars','vote':voteStr,'val':testo}).addClass('current-rating rating_' + testo));//.attr({'id':'curr_stars','value':testo,'vote':voteStr});
    if($('#comm_txt') && $('#comm_txt').val() != '' && $('#comm_txt').val() != 'Scrivi il tuo commento'){
			$('span.pubblica_comm').css({'display':'none'})
			$('a.pubblica_comm').fadeIn(500);
		} else {
  		$('span.pubblica_comm').css({'display':'block'});
  		$('a.pubblica_comm').css({'display':'none'});
		}
    //console.log('Vote: '+$('#curr_stars').attr('val'));
    return false;
})


// Gestione del link "leggi commento" in caso di spoiler nel listing
$('a.leggiSpoilerLink').live("click", function(){
	try{
		var id = this.id.substring(16);
		$('#warningSpoiler'+id).slideUp();
		$('#leggiSpoiler'+id).hide();
		$('#commBody'+id).slideDown();
	}catch(e){
	}
	return false;
})


//-------------------------------------------------------------------------------------------------------
//	F I N E   F U N Z I O N I    A L   C L I C K  - L I V E
//-------------------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------------
//	F U N Z I O N I    A L   C L I C K
//-------------------------------------------------------------------------------------------------------

function associaFunzioniClick(nodeName){

	// Gestione risposte
	$(nodeName+" .risposte").each(function(){
  	var elm = $(this).children('.risposta');
  	if($(this).attr('count') > elm.length){
  	  $(this).prepend($('<div/>').addClass('show_risp').html('<span></span>Leggi tutte le risposte ('+$(this).attr('count')+')'));
  	}
  });

  // Gestione della limitazione di un testo
  $(nodeName+" P").each(function(){
  	  var real_height = $(this).outerHeight();
  	  var real_line = real_height/eval($(this).css('line-height').substr(0,2));
  	  if (real_line > 5) {
  	    $(this).css('height',eval($(this).css('line-height').substr(0,2)*5 -1));
		    inside = $('<span/>').html('+');
  	    $(this).append($('<a/>').addClass('add').attr({'h':real_height,'title':'Leggi tutto'}).html(inside));
  	  }
  });

	function createRel(){
		$('.comm_tools a').each(function(){
			var tempTit = $(this).attr("title");
			$(this).attr	("rel".tempTit);
			$(this).removeAttr("title");
		})
	}

  if (CC.tools) {
    if (!CC.tools.fb) {
      $('.comm_fcb').remove();
    };
    if (!CC.tools.tw) {
      $('.comm_tw').remove();
    };
    if (!CC.tools.prlnk) {
      $('.comm_prlnk').remove();
    };
    if (!CC.tools.piac) {
      $('.comm_piac').remove();
    };
    if (!CC.tools.npiac) {
      $('.comm_npiac').remove();
    };
    if (!CC.tools.sgn) {
      $('.comm_sgn').remove();
    };
  }

  return true;
}

//-------------------------------------------------------------------------------------------------------
//	F I N E    F U N Z I O N I    A L   C L I C K
//-------------------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------------
//	F U N Z I O N I    D I    U T I L I T Y
//-------------------------------------------------------------------------------------------------------

// encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
// This function fixes that limitation
function fixedEncodeURIComponent(str)
{
  return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                 replace(/\)/g, '%29').replace(/\*/g, '%2A');
}

// Funzione che valida l'input dello user (no html tags)
function validateUsrInput(str)
{
  var re = new RegExp(/<[/]?([^> ]+)[^>]*>/g);
  var reEnt = new RegExp("&[^ ;]+;");
  //console.log('[validateUserInput] str to test = '+str);
  if (re.test(str)||reEnt.test(str)) {return false;}
  return true;
}

// Funzione che taglia il testo
function truncateText(node,dim){
  txt = node.html().replace(/<\/?[^>]+(>|$)/gi,' ');
  txt_max = txt.length;
  if(txt_max>dim){
    txt = txt.substr(0, dim);
  }
  return txt;
}

// Funzione che restituisce la data odierna
function user_date(){
	var data_ins = new Date();
	var data_giorno = data_ins.getDate();
	if (data_giorno < 10) data_giorno = '0' + data_giorno;
	var mese=new Array(12);
	mese[0]="Gennaio";
	mese[1]="Febbraio";
	mese[2]="Marzo";
	mese[3]="Aprile";
	mese[4]="Maggio";
	mese[5]="Giugno";
	mese[6]="Luglio";
	mese[7]="Agosto";
	mese[8]="Settembre";
	mese[9]="Ottobre";
	mese[10]="Novembre";
	mese[11]="Dicembre";
	var data_mese = mese[data_ins.getMonth()]
	var data_anno = data_ins.getFullYear();
	var data_ora = data_ins.getHours();
	var data_minuti = data_ins.getMinutes();
	if(data_ins.getMinutes()<10){data_minuti = '0'+data_minuti;}
	return 'il '+data_giorno+' '+data_mese+' '+data_anno+', ore '+data_ora+':'+data_minuti;
}

// Funzione per testare se l'utente e' loggato
function checkLogin(functionType,node){
  CC.activeNode=$(node);
  CC.ajaxFunctionType=functionType;
	if (LV.logged) {
		//console.log("Loggato!");
		CC.serverCall();
	} else {
		//console.log("Non Loggato!");
	  switch (functionType) {
      case 2:
    		LV.titleLogin = "Prima di pubblicare questo commento scegli il tipo di accesso:";
    		LV.labelConfirmButton = "commento";
    		LV.application = "COMMENTI";
  		break;
      case 3:
    		LV.titleLogin = "Prima di pubblicare questa risposta scegli il tipo di accesso:";
    		LV.labelConfirmButton = "risposta";
    		LV.application = "COMMENTI";
  		break;
  	   case 4: case 5:
  		  LV.titleLogin = "Prima di votare scegli il tipo di accesso:";
    		LV.labelConfirmButton = "voto";
    		LV.application = "COMMENTI";
    	break;
      case 9:
    		LV.titleLogin = "Prima della segnalazione, scegli il tipo di accesso:";
    		LV.labelConfirmButton = "segnala spoiler";
    		LV.application = "COMMENTI";
  		break;
       default:
    	  LV.titleLogin = "Scegli il tipo di accesso:";
    		LV.labelConfirmButton = "";
    		LV.application = "COMMENTI";
  	}

		LV.callBackObject = CC;
		LV.callBack = 'serverCall';
		LV.initLogin();
	}
	return false;
}

// Funzione per testare la risporta del server
function checkServerResponse(res){
	if (res.toString().indexOf('<!-- ERRORE:') < 0) {
		return true;
	}
}

// Funzione per testare la risporta del server
function checkText(txt){
  if (CC.voting == 'true' && txt.replace(/^\s+|\s+$/g,'').replace(/<br\>/gi,'') == '') {
    createErrorMessage('ATTENZIONE:<br> Per poter procedere con la pubblicazione &egrave; necessario che tu inserisca un testo.','');
  } else if ( txt.length > 0 && txt.length < 2000 ) {
    if(!validateUsrInput(txt)) {
        createErrorMessage('ATTENZIONE:<br> Hai usato caratteri non consentiti','');
    } else if ( txt == 'Scrivi il tuo commento' ) {
      createErrorMessage('ATTENZIONE:<br> Per poter procedere con la pubblicazione del tuo voto, &egrave; necessario che tu inserisca anche un commento.','');
    } else {
      //testo = testo.replace(/<br\>/gi,'');
  	   if (txt.replace(/^\s+|\s+$/g,'').replace(/<br\>/gi,'') != '')
  	   {
  		   return true;
  	   }
    }
  } else if ( txt.length > 2000 ) {
    createErrorMessage('ATTENZIONE:<br> Il tuo testo &egrave; troppo lungo','');
  }
	return false;
}

// Funzione per testare se esiste una votazione  **LOCAL**
function checkVote(){
  if ( !$('DIV').is('.rating_whi_comm') ) {
    return true;
  }
  if ($('LI').is('#ul-stars #curr_stars') ) {
    return true;
  } else {
    createErrorMessage('ATTENZIONE:<br> Per poter procedere con la pubblicazione del commento, &egrave; necessario che tu esprima anche un voto.','');
  }
  return false;
}

// Funzione per gestire gli errori
function createErrorMessage(msg,err){
  //console.log("ERRORE: " + err);
   if (msg == 'ATTENZIONE:<br> ')
		return false;

  if (msg == '') {
    msg = 'ATTENZIONE:<br> Il servizio non &egrave; al momento disponibile';
  } else {

	  var mess = $('<div></div>').addClass('layerError')
	  .append($('<p></p>').html(msg))
	  .append($('<a></a>').addClass('layer_close').attr({'href':'#','title':'Chiudi'}))
	  .append('<!-- ERRORE: ' + err + ' -->');
	  manageError(mess);
	}
	return false;
}

// Funzione per gestire gli errori
function createAbuseMessage(msg,pos){
  var mess = $('<div></div>').addClass('layerError')
  .append($('<p></p>').html(msg))
  .append($('<a id="abuseConfirm"></a>').addClass('confirm').attr({'href':'#','title':'Conferma','pos':pos}).html('Conferma'))
  .append($('<a></a>').addClass('layer_close').attr({'href':'#','title':'Chiudi'}));
  manageError(mess);
	return false;
}

// Funzione per gestire gli errori
function createSpoilerMessage(msg,pos){
  var mess = $('<div></div>').addClass('layerError').addClass('layerSpoiler')
  .append('<img class="ico-spoiler-big"/>')
  .append($('<p></p>').html(msg))
  .append($('<a id="spoilerConfirm"></a>').addClass('confirm').addClass('spoilerDisclaimer').attr({'href':'#','title':'Conferma','pos':pos}).html('Conferma'))
  .append($('<a></a>').addClass('layer_close').attr({'href':'#','title':'Chiudi'}));
  manageError(mess);
	return false;
}


// Funzione per gestire gli errori
function manageError(msg){
	overlay = $('<div class="overlay"></div>').css({'position':'absolute','left':'0','top':'0','background':'#000','z-index':'100','height':''+$(document).height()+'px','width':''+$(document).width()+'px','opacity':'0.5'});
	$('body').append(overlay);
	$('body').append(msg);
	$('.layerError').css({'left': ($(window).width()/2)-($('.layerError').width()/2),'top': ($(window).height()/2)-($('.layerError').height()/2)});
	$('li a').click(function(){$('li a').removeClass('on');$(this).addClass('on')});
	$('.layer_close').click(function(){$('.layerError').css({'display':'none'});$('.overlay').css({'display':'none'}); return false});
	return false;
}

// Funzione per gestire il risultato di una chiamata Ajax
function createTemp(res){
  $('<div></div>').attr({'id':'commenti_temp'}).html(res.toString()).appendTo("BODY");
  associaFunzioniClick('#commenti_temp');
  return false;
}



//-------------------------------------------------------------------------------------------------------
//	F I N E    F U N Z I O N I    D I    U T I L I T Y
//-------------------------------------------------------------------------------------------------------

$(document).ready(function() {
  // Istanza del RecService
  if (CC.recId != '(none)' && CC.recId !== '' ) {
    CC.REC = new RecService();
  }
  if (CC.staticComm=='TRUE') {
	  associaFunzioniClick('#commenti');
    CC.setHtmlComment();
  } else {
    CC.serverCall();
  }
  return false;
});

