/**
 * @author Riccardo
 */

$(function(){         
    // Dialog			
    $('#dialog_commenti').dialog({

		open: function() { 
						
			var idCommento = $(this).dialog('option', 'id_commento');
			
			if ( ($(this).dialog('option', 'tipo')) && ($(this).dialog('option', 'id_commento')) )
			{
				var tipoCommento = $(this).dialog('option', 'tipo');
				var titoloCommento = $("#boxCommento"+idCommento).find("h4:first").text();
			}
										
			$("button").removeAttr('disabled');
			$("a.ui-dialog-titlebar-close, a.ui-corner-all").css("display","block");

			$("#commento_titolo").removeAttr('disabled');				
			$("#commento_testo").removeAttr('disabled');
			$("#commento_notification").removeAttr('disabled');
				
			$('#errore_titolo').css("display","none");
			$('#errore_testo').css("display","none");
			$('#status_notification').css("display","none");			
			
			if (tipoCommento == 'reply') 
				$('[name=commento_titolo]').val("Re: " + titoloCommento);	
			else 
				$('[name=commento_titolo]').val("");
			
			$('[name=commento_testo]').val(""); 
			$('[name=commento_notification]').attr('checked', false);

		},
        autoOpen: false,
		modal: true,
        width: 600,
		height: 'auto',
		resizable: false,
		closeOnEscape: true,
		position: 'center',
		show: 'blind',
		hide: 'scale',
        buttons: {
            "Annulla": function(){
				
                if (confirm("Desideri annullare l'inserimento del nuovo commento?")) 
				{
					$(this).dialog("close");
				}
            },
            "Invia": function(){
				
				$("button").attr("disabled","disabled");			
				$("a.ui-dialog-titlebar-close, a.ui-corner-all").css("display","none");

				$("#commento_titolo").attr("disabled","disabled");				
				$("#commento_testo").attr("disabled","disabled");
				$("#commento_notification").attr("disabled","disabled");
								
				$('#errore_titolo').css("display","none");
				$('#errore_testo').css("display","none");
				$('#status_notification').css("display","none");		

				$('#status_notification').removeClass("mkmCErrorInfo");					
				$('#status_notification').css("display","block");
				$('#status_notification').addClass("ac_loading");
				$('#status_notification').text("Salvataggio in corso...");
																
				$.post("/commenti", {
															
					media_id_ref: $('[name=media_idref]').val(),

					commento_id_ref: $(this).dialog('option', 'id_commento'),
					
					commento_titolo: $('[name=commento_titolo]').val(),
					commento_testo: $('[name=commento_testo]').val(),
					commento_notification: ($('[name=commento_notification]').is(':checked') ? 1 : 0),										
					
					commento_uri: $('[name=page_uri]').val()+( ($('[name=page_redirect]').val() > 1) ? "/pag/"+$('[name=page_redirect]').val() : '')
					
				}, 					
				function(data)
				{		
						dataJson = eval(data);
												
  						resultXMLHttpRequest = dataJson[0].response;
					
						if (resultXMLHttpRequest == 0)
						{			
							var myCommentDate = $.datepicker.formatDate('DD, d MM yy', new Date(), {dayNames: ['domenica','lunedì','martedì','mercoledì','giovedì','venerdì','sabato'], monthNames: ['gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre']});
			                														
							if ($('#dialog_commenti').dialog('option', 'tipo') == 'new')
							{
								if ($('[name=page_redirect]').val() > 1) {
									
									window.location = $('[name=page_uri]').val()+"#commenti-lista-box";
									
								} else {
									
									nrTotaleCommenti = ($('#nr_totale_commenti').length > 0) ? (parseInt($('#nr_totale_commenti').text())+1) : 1;
																		
									//colorClassHead = ($(".boxCommento").children("div").attr('class') == "mkmCCont mkmC2") ? "mkmCCont" : "mkmCCont mkmC2" ;
									
									colorClassHead = "mkmCCont mkmCNew";
									
									$('#commenti-lista-box').prepend('<div id="boxCommento'+dataJson[0].idcommento+'" class="boxCommento">'+
										'<div class="'+colorClassHead+'">'+ 
											'<div class="mkmCAvatar"><a href="http://forum.zingarate.com/members/'+dataJson[0].user_nickname_sanitized+'-'+dataJson[0].user_id+'.html" target="_blank" title="'+dataJson[0].user_nickname+'"><img src="'+dataJson[0].user_avatar+'" /></a></div>'+
											'<div class="mkmCHead"><a href="http://forum.zingarate.com/members/'+dataJson[0].user_nickname_sanitized+'-'+dataJson[0].user_id+'.html" target="_blank">'+dataJson[0].user_nickname+'</a><span title="'+myCommentDate+'">'+myCommentDate+'</span></div>'+
											'<div class="mkmCText">'+
												'<h4>'+dataJson[0].titolo+'</h4><p>'+dataJson[0].testo+'</p>'+
												'<div id="numero_commento'+dataJson[0].idcommento+'" class="mkmCCount" title="Non ci sono risposte" style="cursor: help;">n°'+nrTotaleCommenti+'</div>'+
												'<div class="mkmCReplyLink">'+
													'<u><span id="nr_risposte'+dataJson[0].idcommento+'">0</span> <span id="testo_risposte'+dataJson[0].idcommento+'">risposte</span></u>'+
													'<span id="show_reply_box'+dataJson[0].idcommento+'"></span>'+
													'<font>|</font>'+
													'<a href="#" id="'+dataJson[0].idcommento+'" class="dialog_commenti_reply" title="Rispondi a questo commento">rispondi</a>'+
												'</div>'+
											'</div>'+
										'</div>'+
										'<div id="boxReplyCommento'+dataJson[0].idcommento+'" class="boxReplyCommento"></div>'+
									'</div>');
																		
									$('#nr_totale_commenti').text(nrTotaleCommenti);
									
									if (nrTotaleCommenti > 0) 
									{									
										if ($('.gallerynew_totcommenti').css('display') == 'none') 
											$('.gallerynew_totcommenti').show();
										
										if ($('.gallerynew_commentifeed').css('display') == 'none') 
											$('.gallerynew_commentifeed').show();
									}
										
								    $('.dialog_commenti_reply').click(function(){        
										$('#dialog_commenti').dialog('option', 'tipo', 'reply').dialog('option', 'id_commento', $(this).attr('id')).dialog('open');
								        return false;
								    });
								}
							} else if ($('#dialog_commenti').dialog('option', 'tipo') == 'reply') {
																							
								colorClassHead = "mkmCCont mkmCNew";
								
								$('#boxReplyCommento'+dataJson[0].idref).prepend('<div id="replyCommento'+dataJson[0].idcommento+'" class="replyCommento">'+
									'<div class="'+colorClassHead+'">'+ 
										'<div class="mkmCAvatar"><a href="http://forum.zingarate.com/members/'+dataJson[0].user_nickname_sanitized+'-'+dataJson[0].user_id+'.html" target="_blank" title="'+dataJson[0].user_nickname+'"><img src="'+dataJson[0].user_avatar+'" /></a></div>'+
										'<div class="mkmCHead"><a href="http://forum.zingarate.com/members/'+dataJson[0].user_nickname_sanitized+'-'+dataJson[0].user_id+'.html" target="_blank">'+dataJson[0].user_nickname+'</a><span title="'+myCommentDate+'">'+myCommentDate+'</span></div>'+
										'<div class="mkmCText">'+
											'<h4>'+dataJson[0].titolo+'</h4><p>'+dataJson[0].testo+'</p>'+
										'</div>'+
									'</div>'+
								'</div>');								
		
								var nr_risposte = ( parseInt($('#nr_risposte'+dataJson[0].idref).text())+1 );
																										
								$('#nr_risposte'+dataJson[0].idref).text(nr_risposte);
								
								if (nr_risposte == 1) 
								{
									$('#show_reply_box' + dataJson[0].idref).html('<font>-</font><a href="#" id="'+dataJson[0].idref+'" class="show_reply" title="Vedi/Nascondi le risposte" onClick="show_reply('+dataJson[0].idref+',this);return false;">nascondi</a>');
									$('#testo_risposte' + dataJson[0].idref).text("risposta");								
												
								} else {
									
									$('#testo_risposte' + dataJson[0].idref).text("risposte");									
								}
								
								$("#numero_commento"+dataJson[0].idref).attr("title","Ultima risposta di "+dataJson[0].user_nickname+" scritto "+myCommentDate+": "+dataJson[0].titolostrlen);
							
								var id_commento = parseInt(dataJson[0].idref);
							
								if ($('#boxReplyCommento' + id_commento).css('display') == 'none') 
								{
									$('#boxReplyCommento' + id_commento).show("slow");
									$('#show_reply_box'+id_commento+' a.show_reply').text('nascondi');
									
								}
							}
														
							$('#dialog_commenti').dialog("close");
		            		
						} else if (resultXMLHttpRequest == 1) {
							
							$("button").removeAttr('disabled');
							$("a.ui-dialog-titlebar-close, a.ui-corner-all").css("display","block");

							$("#commento_titolo").removeAttr('disabled');				
							$("#commento_testo").removeAttr('disabled');
							$("#commento_notification").removeAttr('disabled');
				
							$('#status_notification').removeClass("ac_loading");
							$('#status_notification').css("display","none");
							
							$('#errore_titolo').css("display","block");
							$('#errore_titolo').text("Il titolo del commento non sembra contenere delle parole/frasi di senso compiuto oppure ha troppa punteggiatura.");
						
						} else if (resultXMLHttpRequest == 2) {

							$("button").removeAttr('disabled');
							$("a.ui-dialog-titlebar-close, a.ui-corner-all").css("display","block");

							$("#commento_titolo").removeAttr('disabled');				
							$("#commento_testo").removeAttr('disabled');
							$("#commento_notification").removeAttr('disabled');

							$('#status_notification').removeClass("ac_loading");
							$('#status_notification').css("display","none");
							
							$('#errore_testo').css("display","block");
							$('#errore_testo').text("Il testo del commento non sembra contenere delle parole/frasi di senso compiuto oppure ha troppa punteggiatura.");
						
						} else if (resultXMLHttpRequest == 3) {

							$("button").removeAttr('disabled');
							$("a.ui-dialog-titlebar-close, a.ui-corner-all").css("display","block");

							$("#commento_titolo").removeAttr('disabled');				
							$("#commento_testo").removeAttr('disabled');
							$("#commento_notification").removeAttr('disabled');
							
							$('#status_notification').removeClass("ac_loading");
							$('#status_notification').addClass("mkmCErrorInfo");
							$('#status_notification').css("display","block");
							$('#status_notification').text("Si è verificato un'errore durante il salvataggio. Si prega di riprovare più tardi.");
						}					
					}
				); 					
			}
        }
    });
    
    // Dialog Link
    $('#dialog_commenti_link').click(function(){    
		$('#dialog_commenti').dialog('option', 'tipo', 'new').dialog('option', 'id_commento',0).dialog('open');
        return false;
    });

    $('.dialog_commenti_reply').click(function(){
		
		var id_commento = $(this).attr('id');
				
		var forumDomain = "forum.zingarate.com";

		$.post("/commenti/checkIsLogged/", function(data)
		{											
			resultXMLHttpRequest = data;
			
			if (resultXMLHttpRequest == 0)				
				window.location = 'http://'+forumDomain+'/ucp.php?mode=login&redirect='+$('[name=page_uri]').val()+( ($('[name=page_redirect]').val() > 1) ? "/pag/"+$('[name=page_redirect]').val(): '');
			else
				$('#dialog_commenti').dialog('option', 'id_commento', id_commento).dialog('option', 'tipo', 'reply').dialog('open');
		});
				
		return false;
    });

    $('.show_reply').click(function(){
				
		var id_commento = parseInt($(this).attr('id'));
	
		if ($('#boxReplyCommento' + id_commento).css('display') == 'block') 
		{
			$('#boxReplyCommento' + id_commento).hide("slow");
			$(this).text('vedi');
			
		} else {
		
			$('#boxReplyCommento' + id_commento).show("slow");
			$(this).text('nascondi');
		
		}	
        
		return false;
    });
   
    //hover states on the static widgets
    $('#dialog_commenti_link, ul#icons li').hover(function(){
        $(this).addClass('ui-state-hover');
    }, function(){
        $(this).removeClass('ui-state-hover');
    });
    
});
