/*  Creating variables for storing the previous box, button so that they can be toggled on next click */
var previousReplyBoxId = "";
var previousReplyButtonId = "";
var previousCommentButtonId = "";

/*  Hadnling the page view on page load according to the user's visit - whether he is logged in or not  */
$(document).ready(function() {

  /*  For logged in Users  */
  if ($.cookie('customerToken') != undefined) {

    var customerDetails = JSON.parse($.cookie('customerData'));
    // console.log(customerDetails);

    /*  Fetching the users name and email from cookie, to set it to comment form fields */
    var customerName = customerDetails.firstname +" "+ customerDetails.lastname;
    var customerEmail = customerDetails.email;

    /*  Fetching the user profile picture */
    var customerProfilePicture = "";
    var itemAttributes = customerDetails.custom_attributes;
    $.each(itemAttributes, function(key, value) {
      if (value.attribute_code == "profile_picture") {
        customerProfilePicture = value.value;
        return false;
      }
    });

    /*  Checking the profile picture, if it is working link then setting it to comment box profile picture   */
    checkImage(customerProfilePicture, function() { $('#userProfilePicture').attr("src",customerProfilePicture); }, function(){ } );

    /*  Old code for showing the comment box and hiding the login/regiter box  */
    // $('#userProfilePicture').attr("src",customerProfilePicture);
    // $('#userCommentBox').removeClass("display-none");
    // $('#articleLoginOrRegisterBox').addClass("display-none");

    /* Removing the nonLoggedInUser form so that is won't any problem for Logged in user. */
    $('#nonLoggedInUserCommentBox').remove();

    /*  Setting the data to comment form */
    $('.commentAuthorName').val(customerName);
    $('.commentAuthorEmail').val(customerEmail);
    $('.commentAuthorImageURL').val(customerProfilePicture);

    /*  Showing the reply buttons  */
    $('.comment-reply-button').removeClass('display-none');

    /*  Binding a keyup function to the all comment box so that if an validation error is shown, it should disappear on keyup  */
    $('.comment-box').keyup(function(){
      $('.comment-error').addClass('display-none');
    });

  }else if ($.cookie('commentUserData') != undefined) {
    /*  For non logged in Users but they already commented first time, it is for next time. */
    /*  We already saved a cookie "commentUserData", when they commented first timeout  */
    /*  We are using this cookie to fetch the user details, and setting them to main comment form  */

    /*  Removing the nonLoggedInUser form so that is won't any problem for Logged in user. */
    $('#nonLoggedInUserCommentBox').remove();

    /*  Showing the comment box and reply buttons   */
    $('#userCommentBox').removeClass('display-none');
    $('.comment-reply-button').removeClass('display-none');

    /*  Getting the user data   */
    let commentUserData = JSON.parse($.cookie('commentUserData'));
    // console.log(commentUserData);

    /* Setting the data to the main comment form  */
    $('.commentAuthorName').val(commentUserData.name);
    $('.commentAuthorEmail').val(commentUserData.email);

  }else{
    /*  For non logged in user as well as they are commenting first time.  */
    /*  A user detai form is adding for every comment reply. Also deleting it when user clicks another reply button.  */

    /*  Main comment form id. --- so that when user clicks on reply it should be removed  */
    previousReplyBoxId = "#0";
    previousReplyButtonId = "#0ReplyButtonId";

    /*  Showing the nonLoddedInUserForm4Comment and removing the fields which are present for logged in user */
    /* Removing the form for Logged in Users. */
    $('#userCommentBox').remove();

    /*  Hidding main comment opening button  */
    $('#0CommentButtonId').addClass('display-none');

    /*  Showing the comment box and reply buttons   */
    $('#userDetailBox4LoggedOutUser').removeClass('display-none');
    $('.comment-reply-button').removeClass('display-none');

    // $('#articleLoginOrRegisterBox').removeClass("display-none");
  }
});

function showCommentBox(commentId, version) {

  /* Creating the id's */
  let replyBoxId = '#' + commentId;
  let replyButtonId = '#' + commentId + "ReplyButtonId";
  let commentButtonId = '#' + commentId + "CommentButtonId";

  /* Hiding all errors. */
  $('.comment-error').addClass('display-none');

  /* Hiding previous comment button and comment box. */
  $(previousCommentButtonId).toggle('slow');
  $(previousReplyBoxId).toggle('slow');

  /* Showing previous reply button */
  $(previousReplyButtonId).toggle('slow');

  /* Hiding the cuttently clicked reply button */
  $(replyButtonId).toggle('slow');

  if ($.cookie('customerToken') != undefined) {
    // alert("Logged in ", commentId);
    $(replyBoxId).toggle('slow', function(){
      $(commentButtonId).toggle('slow');
    });
  }else if ($.cookie('commentUserData') != undefined) {
    // alert("Logged out but data filled and saved ", commentId);
    $(replyBoxId).toggle('slow', function(){
      $(commentButtonId).toggle('slow');
    });
  }else {
    hadlingOpeningCommentBoxOfFirstTimeNonLoggedInUser(commentId, version);

    /* Removing the content of previously populated form so that id's won't conflict*/
    $(previousReplyBoxId).html('');
  }

  previousReplyBoxId = replyBoxId;
  previousReplyButtonId = replyButtonId;
  previousCommentButtonId = commentButtonId;

}

/************************************************** Starts **************************************************/
/*Handeling the things when user is not logged in and he want to comment first time ( i.e. user had not filled his details ).  */

function hadlingOpeningCommentBoxOfFirstTimeNonLoggedInUser(commentId, version) {
  /* 1. Create all the id's and variable, which are require for the form operation*/
  /* 2. Renmove the html input field which is already present for logged in user. */
  /* 3. Renmove the continue button which is already present.*/
  /* 4. Removing all this because we are adding a new form using JQuery */
  /* 5. Add the detail form to perticular comment. */

  /* Creating the id's  */
  let replyBoxId = '#' + commentId;
  let commentButtonId = '#' + commentId + "CommentButtonId";
  let newCaptchaId = "commentCaptcha" + commentId;

  let replyButton = "POST REPLY";

  /*  While populating the form, if it is first level comment Box then button should be "Comment" otherwise "REPLY"   */
  if(commentId == 0)
    replyButton = "POST COMMENT";

  /* User detail Form node as a variable, so that we can append it to required div */
  let newForm = $('<form id="nonLoddedInUserForm4Comment" method="post">' +
                '<div class="form-group full-width pull-left" id="userDetailBox4LoggedOutUser">' +
                          '<div class="col-md-12 col-xs-12">' +
                            '<span style="padding: 10px 0; font-size: 18px; font-weight: bold;">' +
                              'Fill out the form or ' +
                                '<a class="border-bottom-red text-decoration-none" href="#" onclick="getLogUrlForComment()">Login</a>' +
                                ' / ' +
                                '<a class="border-bottom-red text-decoration-none" href="#" onclick="getRegUrlForComment()">Register</a>' +
                                ' to comment:' +
                            '</span>' +
                          '</div>' +
                          '<div class="col-md-12 col-xs-12">' +
                            '<i><span class="red" style="">(All fields required)</span></i>' +
                          '</div>' +
                          '<div class="col-md-6 col-xs-12 mt_10">' +
                           ' <input type="text" class="user-detail-input-first-name non-logged-in-input" placeholder="First Name" name="commentContent" oninvalid="this.setCustomValidity(\'First Name should not be empty\')"  oninput="setCustomValidity(\'\')" required>' +
                            '<i><p class="red display-none comment-error">First Name should not be empty !!!</p></i>' +
                          '</div>' +
                          '<div class="col-md-6 col-xs-12 mt_10">' +
                           '<input type="text" class="user-detail-input-last-name non-logged-in-input" placeholder="Last Name" name="commentContent" oninvalid="this.setCustomValidity(\'Last Name should not be empty\')"  oninput="setCustomValidity(\'\')" required>' +
                            '<i><p class="red display-none comment-error">Last Name should not be empty !!!</p></i>' +
                         ' </div>' +
                          '<div class="col-md-12 col-xs-12 mt_10">' +
                           ' <input type="email" class="user-detail-input-email non-logged-in-input" placeholder="email" name="commentContent" required>' +
                           ' <i><p class="red display-none comment-error">email should not be empty !!!</p></i>' +
                         ' </div>' +
                         ' <div class="col-md-12 col-xs-12 mt_10 mb_10">' +
                            // '<input type="text" class="user-detail-input-comment comment-box non-logged-in-input" placeholder="Type your comment here" name="commentContent" oninvalid="this.setCustomValidity(\'Comment should not be empty\')"  oninput="setCustomValidity(\'\')" required>' +
                            '<textarea rows="4" cols="10" class="unset-height user-detail-input-comment comment-box non-logged-in-input" placeholder="Type your comment here" name="commentContent" oninvalid="this.setCustomValidity(\'Comment should not be empty\')"  oninput="setCustomValidity(\'\')" required></textarea>' +
                            '<i><p class="red display-none comment-error">Comment should not be empty !!!</p></i>' +
                          '</div>' +
                          '<input type="text" value="' + version + '" id="showBoxVersion"/>' +
                         /*   Comment as the guest user checkbox  */
                         // ' <div class="col-md-12 form-group required">' +
                         //  '  <input class="small-checkbox" style="width:auto;" type="checkbox" id="commentAgreeTerms" name="agreeTerms">' +
                         //  '  <label class="small-checkbox" for="commentAgreeTerms">Comment as the guest user</label>' +
                         //  '  <i><p class="red display-none comment-error commentAgreeTermsAlert">You should check the checkbox.</p></i>' +
                         //  '</div>' +
                          '<div class="col-md-12 col-xs-12">' +
                            '<div class="col-md-6 p_0">' +
                              '<div id="' + newCaptchaId +'" class="g-recaptcha"></div>' +
                              '<i><p class="red comment-error display-none" id="captchaIsNotChecked">Please check the reCaptcha</p></i>' +
                            '</div>' +
                            '<div class="full-width pull-left pt_0 hide" id="commentCaptchaIsNotVerified">' +
                              '<label class ="redError">Something went wrong with Captcha Verificatioin. Please refresh and try again!</label>' +
                            '</div>' +
                            '<div class="col-md-12 p_0">' +
                              '<span class="pull-right">' +
                               // ' <button class="comment-reply-button p_0" id="continueCommentButton">COMMENT</button>' +
                               ' <button class="comment-reply-button p_0" id="continueCommentButton">' + replyButton + '</button>' +
                               '<span id="post-comment-loader" class="display-none"><i class="fa fa-spinner fa-spin red post-comment-loader"></i></span>' +
                              '</span>' +
                            '</div>' +
                         ' </div>' +
                         // ' <hr class="border-bottom full-width pull-left mt_30">' +
                '</div>' +
            '</form>' );

  /* Removing the thing's ( as mentioned in point 2 & 3 ) */
  $(replyBoxId).html('');
  $(commentButtonId).remove();

  /* Adding form to comment */
  $(replyBoxId).html(newForm);

  /* Adding the reCaptch to the form. */
  loadCaptcha(newCaptchaId);

  /* Show the form to the user */
  $(replyBoxId).toggle('slow');

  /*  Adding required attribute to input fields */
  $('input.non-logged-in-input').each(function() {
      $(this).attr("required", true)
  });

  /* Binding the hover function to reCaptcha */
  $('.g-recaptcha').hover(function() {
    setTimeout(function(){
      $("#captchaIsNotChecked").addClass("display-none");
    }, 1000)
  });

  // alert("Logged in but data is not filled " + commentId);
}

/*************************************************** End ****************************************************/

// Submiting the Replies to Comments
var previousErrorId = "";
function onClickReplyToComment(parentId, replyBoxId, version){
  $(previousErrorId).addClass('display-none');

  var replyBox = '#' + replyBoxId + ' > textarea';
  var replyContent = $(replyBox).val();
  replyContent = '<p>'+replyContent.replace(/\r\n|\r|\n/g,"<br />")+'</p>';
  var errorId = '#' + parentId + "Error";

  // console.log(replyBox);

  if(replyContent==""){
    $(errorId).removeClass('display-none');
    previousErrorId = errorId;
    return false;
  }

  $('#replyCommentParentId').val(parentId);
  $('#replyCommentContent').val(replyContent);
  $('#replyCommentVersion').val(version);

  $('#replyCommentForm').submit();
}

function onClickReplyToComment4Loggedout(){

  let version = $('#showBoxVersion').val();
  let commentId = $('#nonLoddedInUserForm4Comment').parent().attr('id');
  var replyContent = $('.user-detail-input-comment').val();
  replyContent = '<p>'+replyContent.replace(/\r\n|\r|\n/g,"<br />")+'</p>';

  if(replyContent==""){
    $('.user-detail-input-comment + i > p').removeClass('display-none');
    $('#post-comment-loader').addClass('display-none');
    $('#continueCommentButton').removeClass('display-none');
    return false;
  }

  $('#replyCommentParentId').val(commentId);
  $('#replyCommentContent').val(replyContent);
  $('#replyCommentVersion').val(version);

  $('#replyCommentForm').submit();
}

function checkImage(imageSrc, good, bad) {
    var img = new Image();
    img.onload = good;
    img.onerror = bad;
    img.src = imageSrc;
}

var clickOfCommentBox = 2;
function viewMoreComments(lastCommentBox){
  var fiveCommentBoxId = '#five-comment-box-' + clickOfCommentBox;

  if(clickOfCommentBox < lastCommentBox){
    clickOfCommentBox++;
    $(fiveCommentBoxId).toggle(3000);
  }else if(clickOfCommentBox == lastCommentBox){
    clickOfCommentBox++;
    $(fiveCommentBoxId).toggle(3000, function(){
      $(fiveCommentBoxId).css({'display':'block'})
      // $('#viewMoreCommentsButton').addClass('red');
      // $('#viewMoreCommentsButton').text('No More Comments !!!');
      // $('#viewMoreCommentsButton').attr('disabled','disabled');
      $('#viewMoreCommentsButton').remove();
    });
  }else{
    clickOfCommentBox++;
    $(fiveCommentBoxId).css({'display':'block'})
    // $('#viewMoreCommentsButton').addClass('red');
    // $('#viewMoreCommentsButton').text('No More Comments !!!');
    // $('#viewMoreCommentsButton').attr('disabled','disabled');
    $('#viewMoreCommentsButton').remove();
  }
}

/*  Submiting the comments form a non logged in user who comments first time  */
/*  This form is just for getting the details of user and validating all the input.  */
/*  Once all the validation are done, the values are set to main comment form and we will submit that form, not this one. */
$(document).on("submit", "#nonLoddedInUserForm4Comment", function(e){

    e.preventDefault();

    /* Even though html validation are present, we add our own validation for more security */
    /* From this form we will get either false OR else we'll get captcha response   */
    let reCaptchaResponse = validateCommentUserForm();

    /*  If all the fields are filled and are all valid then checking reCaptcha*/
    /*  Validating the reCaptcha */
    /*  If reCaptcha is validated with backend then setting the values to main comment form and submitting that form  */
    if(reCaptchaResponse){

      $('#continueCommentButton').addClass('display-none');
      $('#post-comment-loader').removeClass('display-none');

      let captchaVerifyURL = APIBaseUrl+"recaptcha/siteverify";
      let captchaVerificationData = {
                   "response": reCaptchaResponse
                 };

      $.ajax({
          url: captchaVerifyURL,
          type: 'POST',
          contentType: 'application/json',
          data: JSON.stringify(captchaVerificationData),
          success: function(data, textStatus) {
            // console.log("captchaVerifyURL data : " + data);

            /*  If reCaptcha Validation fails then showing the error.*/
            if(!data){
              $('#commentCaptchaIsNotVerified').removeClass('hide');
              $('#post-comment-loader').addClass('display-none');
              $('#continueCommentButton').removeClass('display-none');
              e.preventDefault();
              return false;
            }

            /*  If reCaptcha Validation success then proceding further.*/
            /*  Getting the firstname, lastname, email values from form field*/
            let nonLoggedUserName = $('.user-detail-input-first-name').val() + " " + $('.user-detail-input-last-name').val();
            let nonLoggedUserEmail = $('.user-detail-input-email').val();

            // Setting the data to main comment form
            $('.commentAuthorName').val(nonLoggedUserName);
            $('.commentAuthorEmail').val(nonLoggedUserEmail);

            /*  Saving the nonLoggedInUser's data into cookie for future use  */
            let commentUserData = {
              "name" : nonLoggedUserName,
              "email" : nonLoggedUserEmail
            }
            $.cookie('commentUserData', JSON.stringify(commentUserData), {expires: 7});

            onClickReplyToComment4Loggedout();

          },
          error: function(request, textStatus, errorThrown) {
            $('#post-comment-loader').addClass('display-none');
            $('#continueCommentButton').removeClass('display-none');
            return false;
          }
       });
    }

    return  false;
});

function validateCommentUserForm(){

  $('.comment-error').addClass('display-none');

  // Checking if First Name is empty, if yes then showing the error
  if ($('.user-detail-input-first-name').val() == "") {
    $('.user-detail-input-first-name + i > p').removeClass('display-none');
    return false;
  }

  // Checking if Last Name is empty, if yes then showing the error
  if ($('.user-detail-input-last-name').val() == "") {
    $('.user-detail-input-last-name + i > p').removeClass('display-none');
    return false;
  }

  // Checking if email is empty, if yes then showing the error
  if ($('.user-detail-input-email').val() == "") {
    $('.user-detail-input-email + i > p').removeClass('display-none');
    return false;
  }

  // Checking if Comment is empty, if yes then showing the error
  if ($('.user-detail-input-comment').val() == "") {
    $('.user-detail-input-comment + i > p').removeClass('display-none');
    return false;
  }

  /*  code for Comment as the guest user Checkbox  */
  // Checking if User checked the "Guest checkbox" OR not.
  // if (!$('#commentAgreeTerms').prop('checked')) {
  //   $('.commentAgreeTermsAlert').removeClass('display-none');
  //   return false;
  // }

  // Checking if User checked the reCaptchs OR not.
  let reCaptchaResponse = getReCaptcharesponse();
  if (!reCaptchaResponse) {
    $("#captchaIsNotChecked").removeClass("display-none");
    return false;
  }else {
    return reCaptchaResponse;
  }

  return true;
}

$('.g-recaptcha').hover(function() {
  setTimeout(function(){
    $("#captchaIsNotChecked").addClass("display-none");
  }, 1000)
});
