var clickedId;
var tmpCommentTa = '<textarea cols="50" rows="2" style="height: 25px; margin-bottom:15px; margin-top:5px;" id="tmp_comment_body" placeholder="Inserisci il tuo commento"></textarea>';//overflow-x: hidden; overflow-y: hidden;
var fbSpinner = '<img id="fbSpinner"  src="/static/images/fb-spinner.gif" alt="..." />';
var commentBlock = '<li class="commentLine"><div id="tmp_add_comment">'+tmpCommentTa+fbSpinner+'<input type="button" id="tmp_submit" value="Commento" /></div></li>';
var subcommentBlock = 0;
var rightNow = "in questo momento";
$(function() {

     $('.show-petition').toggle(function(){
        $(this).find('span').text(messages.hidePet);
        $('#lastText').show();
        $('#crop').hide();
        $('.cropText').hide();
    },function(){
        $(this).find('span').text(messages.showPet);
        $('#lastText').hide();
        $('#crop').show();
        $('.cropText').show();
        $('html, body').animate({scrollTop: $('.progressbar').offset().top}, 1000);
    });

  var start = 3;var firstClick = 0;

 $('.comment-on-comment').live('click',function(){
    if($('#tmp_add_comment').length <=0){
        $(this).parent().parent().before(commentBlock);
    }else {
        $('#tmp_add_comment').remove();
        if($(this).attr('id') != clickedId){
                $(this).parent().parent().before(commentBlock);
        }
    }
    clickedId = $(this).attr('id');
});

$('.comment-on-petition').live('click',function(){
    if($('#tmp_add_comment').length <=0){
        $(this).parent().parent().after(commentBlock);
    }else {
        $('#tmp_add_comment').remove();
        if($(this).attr('id') != clickedId){
            $(this).parent().parent().after(commentBlock);
        }
    }
    clickedId = $(this).attr('id');
});

  var addComments = function(data, user)
  {
      var html = '';
      var i = 0;

      for (var k = 0  in data) {
          if (typeof(data[i]) !== 'function') {
              var value = data[i];

              html += '<li class="addcomments">';

              html+= value['comment'] +
                      '<br/>' +
                      '<span class="regTime">'
                      + value['registration_datetime'] +
                      '</span>' +
                      '<span class="user-commented">'
                      + value['first_name'] + '&nbsp' + value['last_name']
                      + '</span>'

                  //add foreach cycle;
                  html += '<ul class="sub-comments" id="' + value['comment_id'] + '">'
                  for (var key in value['subcomments']) {
                    val = value['subcomments'][key];
                    html += '<li>';
                    if(user['loggedUser'] == val['user_id']) {
                        html += '<a href="javascript:void(0);" class="removeComment" title="Rimuovi" id="subcomment-'+ val['comment_id']+'"></a>';
                    }

                    html+= val['message'] + '<br/>'
                            + '<span class="regTime">'
                                + val['registration_datetime']
                            + '</span>'
                            + '<span class="user-commented">'
                                + val['first_name'] + ' ' + val['last_name']
                            + '</span>';

                    html+= '</li>';
                  }
                  html+='<li id="'+ user['petitionId'] +'-'+ value['comment_id']+ '" class="subcomment_buttons"><span>';
                  if(user['logged']) {
                      html += '<span class="comment-on-comment" id="comment-'+ user['petitionId'] +'-'+ value['comment_id']+ '">'
                      + commentComment
                      + '</span>';
                  }
                  html+='</span></li>';

                  html += '</ul></li>';
          }
          i++;
      }
      $("#spinner-container").remove();
      $("#"+user['petitionId']).before(html);
  }

    var load = function(id, start)
    {
        $.ajax({
                url: '/petition/searchcommentsxhr',
                type: 'post',
                data: {'id' : id, 'start' : start},
                dataType: 'json',
                success: function(data) {
                        comments = [];
                        if(data.comments.length < 10 && start > 30) {
                            $("li#"+data.user['petitionId']).remove();
                        }
                        if (data.comments.length) {
                            comments = data.comments;
                            user = data.user
                            addComments(comments, user);
                        }
                }
        });
    }

    $('.show_subcomment').live('click',function(){
         var subdata = $(this).attr('subdata');
         $('.sub-'+subdata).show();
         $('.last-'+subdata).hide();
    });

     $('.return_subcomment').live('click',function(){
        var subdata = $(this).attr('subdata');
        $('.sub-'+subdata).hide();
        $('.last-'+subdata).show();
     });

     $('.show-comment').live('click',function(){
         var id = $(this).parent().attr('id');
         var total = $(this).attr('total');
//         if (firstClick > 0) {
            setClassSpinner('.ms-comments');
            load(id, start);
            start+= 10;
//        }
//        firstClick++;
        $('.'+id).show();
        if(total < 10) {
            $("li#"+id).remove();
        }
     });
      $('.return_comment').live('click',function(){
        start = 3;
        firstClick = 0;
        var id = $(this).attr('number');
        $('.'+id).hide();
        $('.addcomments').remove();
     });

 $('#tmp_comment_body').live('keypress',function (){
     $('#tmp_comment_body').css({'border':'1px solid #ccc'});
 });

 $('#tmp_submit').live('click',function(){
    if($('#tmp_comment_body').val().length >0){
        setSpinner();
    	$('#tmp_submit').addClass('opacity');
    	$('#tmp_submit').attr('disabled', true);

    	$.ajax({
			url: '/index/add-comment-xhr',
			type: 'post',
			data: {
				"data": clickedId,'message':$('#tmp_comment_body').val(), "well":1
			},
			dataType:'json',
			timeout: 50000,
			success: function(data){
                if (data.user['first_name'] !== 'undefined') {
                    if (data.user['type'] === 'comment') {
                        var textComment = '<li>'
                                + $('#tmp_comment_body').val()
                                +'<a href="javascript:void(0);" class="removeComment" title="Rimuovi" id="subcomment-'
                                + data.user['subcomment_id']+'"></a>'
                                + '<br/>'
                                + '<span class="regTime">' +rightNow+'</span>'
                                + '<span class="user-commented">'
                                + data.user['first_name'] + ' ' + data.user['last_name']
                                + '</span></li>';
                        $('#' + data.user['pet_id'] + '-' + data.user['comment_id']).before(textComment);
                    } else {
                          var text = '<li>'
                              + $('#tmp_comment_body').val() +
                              +'<a href="javascript:void(0);" class="removeComment" title="Rimuovi" id="subcomment-'
                                + data.user['subcomment_id']+'"></a>'
                                + '<br/>'
                                + '<span class="regTime">' +rightNow+'</span>'
                              '<span class="user-commented">'
                              + data.user['first_name'] + '&nbsp' + data.user['last_name']
                              + '</span>';
                          if(userAuth) {
                              text += '<span class="comment-on-comment" id="comment-'+ petitionId +'-'+ data.user['comment_id']+ '">'
                                  + commentComment
                                  + '</span>';
                          }
                          text += '<ul class="sub-comments" id="' + data.user['comment_id'] + '"></ul></li>';
                        $('.all-comments').prepend(text);
                    }

$("#tmp_add_comment").slideUp(100);
//$('html, body').animate({scrollTop: $('.ms-comments:first-child').offset().top}, 700);
                } else {
                    alert("Something is going wrong. Please retry later");
                }
			},
			error: function(){
			    $('#tmp_submit').removeAttr('disabled');
			    $('#tmp_submit').removeClass('opacity');
			}
		});
    } else {
    	$('#tmp_comment_body').css({'border':'1px solid red'});
    }
 });

  $('.removeComment').live('click',function(){
      if (subcommentBlock == 0) {
          subcommentBlock = 1;
          var cid = $(this).attr('id').split('-')[1];
          var _this;
          _this = $(this);
          _this.addClass('tmpRemovingComment');

            $.ajax({
                url: '/index/remove-comment-xhr',
                type: 'post',
                data: {
                    "cid": cid//, "uid":uid
                },
                timeout: 10000,
                success: function(content){
                    _this.addClass('commentRemoved');
                    setTimeout(function(){
                        _this.parent().slideUp('slow', function() {
                            refreshData();
                        });
                    }, 1000);
                }
            });
      }
    return false;
 });

});

function refreshData()
{
	$.ajax({
		url: '/petition/refreshcommentxhr',
		type: 'post',
		data: {
			"petId": petitionId
		},
		timeout: 50000,
		success: function(content){
                        subcommentBlock = 0;
			$("#comments-results").html(content);
			$("#comments-results").fadeTo(100, 1);
		}
	});
}

function setSpinner (){
    $('#fbSpinner').css('display','block');
}
function setClassSpinner (inputClass){
    $(inputClass).append('<div id="spinner-container"><img src="/static/images/ajax-loader.gif" alt="Loading.." /></div>');
}

