/* Minification failed. Returning unminified contents.
(1,27): run-time error CSS1031: Expected selector, found '='
(1,27): run-time error CSS1025: Expected comma or open brace, found '='
(540,96): run-time error CSS1002: Unterminated string: 't reviewed yet</h3>
(564,101): run-time error CSS1002: Unterminated string: 't completed your review</h3>
(610,1): run-time error CSS1019: Unexpected token, found '$'
(610,2): run-time error CSS1019: Unexpected token, found '('
(610,11): run-time error CSS1031: Expected selector, found ')'
(610,11): run-time error CSS1025: Expected comma or open brace, found ')'
(612,2): run-time error CSS1019: Unexpected token, found ')'
 */
var OwnerVoteCommentEvent = {
    init: function () {
        if ($('#hddBrandId').length == 0)
            return;

        if ($('#hddModel').length == 0)
            return;

        if ($("#commentBoxContainer").length > 0) {

            //init event write comment
            $("#btnWriteYourReview").on('click', function () {
                if (OwnerVoteCommentEvent.checkLogin()) {
                    var brandId = $(this).attr("data-brand");
                    var modeId = $(this).attr("data-model");
                    var type = $(this).attr("data-type");
                    PostForm.LoadPopupFromUrl("/OwnerReview/WriteReview", { brandId: brandId, modelId: modeId, articleType: type }, function () {
                        OwnerVoteCommentEvent.initEvent();
                    });
                }
            });
            //init event tab change
            $("#commentBoxContainer .memnu-owner-reviews li").on('click', function () {
                //hide tab
                $("#commentBoxContainer .memnu-owner-reviews li a").removeClass("active");
                $("#commentBoxContainer #lsComment").children().hide();
                //show active tab
                var activeTab = $(this)[0];
                OwnerVoteCommentEvent.reviewMenuChange(activeTab);
            });
            if ($('#lsComment').length > 0) {
                OwnerVoteCommentEvent.initCommentDetail();
            }
        }

        OwnerVoteCommentEvent.currentTab = 1;
        OwnerVoteCommentEvent.dataChange = false;
        OwnerVoteCommentEvent.getListCommentInfo(0, 0, 0, 1);
    },

    initEvent: function () {
        //OwnerVoteCommentEvent.initEventKeyUp();
        initVotetingEvent = function (voteElm) {
            //Set star trong vote
            if (!voteElm) voteElm = $('.voteOwner.active');
            $(voteElm).find('.voting').on(
                {
                    mouseover: function () {
                        if ($('#btnSubmitOwnerVote').length) {
                            var ratePoint = parseFloat($(this).data("rate"));
                            var voteOwner = $(this).parent().closest(".rating");
                            OwnerVoteCommentEvent.activeRate(voteOwner, ratePoint);
                        }
                    },
                    mouseout: function () {
                        if ($('#btnSubmitOwnerVote').length) {
                            var voteOwner = $(this).parent().closest(".voteOwner .rating");
                            var ratePoint = parseFloat(voteOwner.attr("data-value"));
                            if (isNaN(ratePoint)) ratePoint = 0;
                            OwnerVoteCommentEvent.activeRate(voteOwner, ratePoint);
                            OwnerVoteCommentEvent.dataChange = true;
                        }
                    },
                    click: function () {
                        if ($('#btnSubmitOwnerVote').length && OwnerVoteCommentEvent.checkLogin()) {
                            var ratePoint = parseFloat($(this).data("rate"));
                            var voteOwner = $(this).parent().closest(".voteOwner .rating");
                            OwnerVoteCommentEvent.activeRate(voteOwner, ratePoint);
                            voteOwner.attr("data-value", ratePoint);
                            $(voteOwner).parent().find(".text-erro").addClass("hidden");
                        }
                    }
                }
            );
        };

        $('.voteOwner textarea').on('keyup', function () {
            if ($(this).val().trim().length > 0) {
                $(this).parent().find(".text-erro").addClass("hidden");
            }
            OwnerVoteCommentEvent.dataChange = true;
        });

        if ($('#btnSubmitOwnerVote').length > 0) {
            OwnerVoteCommentEvent.initSubmitVote();
        } else {
            $('.carguide-review-content').addClass('read');
            $('.carguide-review-content textarea').prop('readonly', true);
        }

        $('.btn-edit').click(function () {
            if (OwnerVoteCommentEvent.checkLogin()) {
                if ($('#btnSubmitOwnerVote').length) {
                    //show textbox
                    $(this).parent().removeClass("done");
                    var boxForm = $(this).parent().find("textarea");
                    if (boxForm !== void (0) && boxForm.length > 0) {
                        boxForm[0].focus();
                        boxForm[0].setSelectionRange(boxForm[0].value.length, boxForm[0].value.length);
                    }
                    //voting
                    initVotetingEvent($(this).parent());
                }
            }
        });

        $(".btn-done").click(function () {
            var reviewContainer = $(this).parent().parent().parent();
            if (OwnerVoteCommentEvent.CheckRatetingAndComment(reviewContainer)) {
                let boxForm = $(reviewContainer).find("textarea");
                let displayEl = $(reviewContainer).find('.box-text-cm .text-cm');
                if (boxForm !== void (0) && boxForm.length > 0 && displayEl !== void (0)) {
                    displayEl.text(boxForm[0].value);
                    reviewContainer.addClass('done');
                }
            }
        });

        $('.btn-write-comment').click(function () {
            if (OwnerVoteCommentEvent.checkLogin()) {
                $(this).parent().addClass("active");
                var boxForm = $(this).parent().find("textarea");
                if (boxForm !== void (0) && boxForm.length > 0) {
                    boxForm[0].focus();
                    boxForm[0].setSelectionRange(boxForm[0].value.length, boxForm[0].value.length);
                }
                //voting
                initVotetingEvent($(this).parent());
            }
        });

        $('.btnWriteYourReview').click(function () {
            $(".box-write-review").hide();
            $(".box-write-desc").hide();
            $(".box-carguide-review").removeClass("hide");
        });

        //Init content vote owner
        OwnerVoteCommentEvent.initContentOwner();

        if (document.location.href.indexOf('#reviews') != -1) {
            $('#modelGuideMenu [data-href=reviews] ').click();
            if (typeof AccountEvent != 'undefined') {
                Utility.RemoveHashTag();
            }
            else {
                RemoveHashTag();
            }
        }
        $("#popWriteReview .close").on('click', function (e) {
            if (OwnerVoteCommentEvent.dataChange) {
                e.stopPropagation();
                OwnerVoteCommentEvent.confirmCloseReview();
            }
        })
        initVotetingEvent();
    },

    initContentOwner: function () {
        $(".voteOwner .rating").each(function (index, value) {
            if ($(value).attr('data-value') > 0) {
                OwnerVoteCommentEvent.activeRate($(this), $(value).attr('data-value'));
            }
        })
    },

    checkLogin: function () {
        var userId = $("#hddUserId").val();
        if (userId == undefined || userId == '0') {
            if (typeof AccountEvent != 'undefined') {
                AccountEvent.ShowPopupLogin();
            } else {
                OpenPopupLogin();
            }
            return false;
        }
        return true;
    },

    initSubmitVote: function () {
        $('#btnSubmitOwnerVote').click(function () {
            if (Utility.IsDoubleClicked($(this))) {
                return;
            }
            //validate data
            if (!OwnerVoteCommentEvent.checkLogin() || !OwnerVoteCommentEvent.validateReviewBeforeSubmit()) return false;

            var dataType = 'application/json; charset=utf-8';
            var data = {
                NumAesthetics: $("#NumAesthetics").attr('data-value'),
                NumSafetyTech: $("#NumSafetyTech").attr('data-value'),
                NumPerformance: $("#NumPerformance").attr('data-value'),
                NumComfortPractical: $("#NumComfortPractical").attr('data-value'),
                NumValueMoney: $("#NumValueMoney").attr('data-value'),
                NoteAesthetics: $("#txtAesthetics").val(),
                NoteSafetyTech: $("#txtSafetyTech").val(),
                NotePerformance: $("#txtPerformance").val(),
                NoteComfortPractical: $("#txtComfortPractical").val(),
                NoteValueMoney: $("#txtValueMoney").val(),
                Content: $("#txtContent").val(),
                BrandId: $("#hddBrandId").val(),
                ModelId: $("#hddModel").val(),
            }

            $.ajax({
                type: "POST",
                cache: false,
                url: '/OwnerReview/CommentOwnerPost',
                dataType: 'json',
                contentType: dataType,
                data: JSON.stringify(data),
                success: function (response) {
                    if (response.Error) {
                        alert(response.Title);
                    }
                    else {
                        $('#btnSubmitOwnerVote').remove();
                        OwnerVoteCommentEvent.showMessageSuccess();
                        // update số comment trên các tab menu
                        OwnerVoteCommentEvent.updateReviewCountNumber();
                        //reload comment list
                        $("#lsComment").children().remove();
                        OwnerVoteCommentEvent.getListCommentInfo(0, 0, 0, OwnerVoteCommentEvent.currentTab);
                    }
                }
            });
        });
    },

    activeRate: function (voteOwner, rateint) {
        if (isNaN(rateint))
            return false;
        //clear error message
        voteOwner.parent().find(".error-vote").addClass("hidden");

        voteOwner.find('i').each(function () {
            var rating = $(this).find('span:first-child').data("rate");
            if (rating == rateint) {
                $(this).attr("class", "icon star-50");
            }
            else if (rating <= rateint) {
                $(this).attr("class", "icon star-yellow");
            }
            else
                $(this).attr("class", "icon star-none");
        });
    },

    validateReviewBeforeSubmit() {
        var result = true;
        $(".voteOwner.active").each(function (index, value) {
            result = OwnerVoteCommentEvent.CheckRatetingAndComment(value) && result;
        })
        //check co it nhat 1 tieu chi dc danh gia
        if (result) {
            var rated = $(".voteOwner").find(".rating .icon.star-yellow");
            if (rated.length == 0) {
                OwnerVoteCommentEvent.showMessageError();
                return false;
            }
        }
        return result;
    },

    CheckRatetingAndComment(reviewCtn) {
        var result = true;
        var rateEl = $(reviewCtn).find(".rating .icon.star-yellow");
        var reviewEl = $(reviewCtn).find(".box-form textarea");
        let reviewContent = reviewEl.length > 0 ? reviewEl.val().trim() : "";
        if (rateEl.length == 0 && reviewContent.length > 0) {
            $(reviewCtn).find(".b-left .text-erro").removeClass("hidden");
            result = false;
        }
        if (reviewContent.length == 0 && rateEl.length > 0) {
            $(reviewCtn).find(".box-form .text-erro").removeClass("hidden");
            result = false;
        }
        return result;
    },

    PostReplyComment: function (parentid, comment, brandId, modelId) {
        if (parentid == 0 || brandId == 0 || brandId == undefined || modelId == 0 || modelId == undefined || comment == undefined || comment == '') {
            return false;
        }
        var dataType = 'application/json; charset=utf-8';
        var data = {
            ParentId: parentid,
            Content: comment,
            BrandId: brandId,
            ModelId: modelId,
        }
        switch (OwnerVoteCommentEvent.currentTab) {
            case 1:
                data.NoteAesthetics = comment;
                break;
            case 2:
                data.NoteSafetyTech = comment;
                break;
            case 3:
                data.NotePerformance = comment;
                break;
            case 4:
                data.NoteComfortPractical = comment;
                break;
            case 5:
                data.NoteValueMoney = comment;
                break;
        }

        $.ajax({
            type: "POST",
            cache: false,
            url: '/OwnerReview/CommentOwnerPost',
            dataType: 'json',
            contentType: dataType,
            data: JSON.stringify(data),
            success: function (response) {
                if (response.Error) {
                    alert(response.Title);
                }
                else {
                    $('.lst-comment-child-' + parentid).append(response.Obj);
                    $('.input-child-' + parentid).removeClass("no-child");
                }
            }
        });
    },

    updateReviewCountNumber() {

        $.ajax({
            type: "GET",
            url: '/OwnerReview/StatisticCarGuideComment',
            data: {
                brandId: $("#hddBrandId").val(),
                modelId: $("#hddModel").val(),
                articleType: $("#hddArticleType").val()
            },
            success: function (data) {
                if (data != null) {
                    $("#txtTotalReview").text("By " + data.TotalNumberOfComment + " car owner reviews");
                    $("#txtRateSummary").text(data.Rate + "/5");
                    $("#numAesthetics").text(data.NumberOfAesthetics);
                    $("#numSafetyTech").text(data.NumberOfSafetyTech);
                    $("#numPerformance").text(data.NumberOfPerformance);
                    $("#numComfortPractical").text(data.NumberOfComfortPractical);
                    $("#numValueMoney").text(data.NumberOfValueMoney);
                }
            }
        });
    },

    initCommentDetail() {
        $('#lsComment').on("click", ".wr_like", function () {
            OwnerVoteCommentEvent.likeUnLike(this, 1);
        });
        $('#lsComment').on("click", ".wr_unlike", function () {
            OwnerVoteCommentEvent.likeUnLike(this, 2);
        });

        //click reply
        $('#lsComment').on("click", ".reply", function () {
            if (OwnerVoteCommentEvent.checkLogin()) {
                var parentId = $(this).data("id");
                $('#ParentId').val(parentId);
                var urlAvatarUserLogin = $('#box-user .box-name-acc .name img').attr('src');
                $('.box-input-comment .avatar img').attr('src', urlAvatarUserLogin);
                $('.box-input-comment').hide();
                if ($("#lst-comment-child-" + parentId + " .list-acc").length > 0) {
                    $('.input-child-' + parentId).removeClass("no-child");
                } else {
                    $('.input-child-' + parentId).addClass("no-child");
                }
                $('.input-child-' + parentId).show();
                $('.txtReply-' + parentId).focus();
            }
        });

        $('#lsComment').on('click', '.btnSubComment', function () {
            if (OwnerVoteCommentEvent.checkLogin()) {
                var parentId = $(this).attr("data-id");
                var brandId = $(this).attr("data-brandid");
                var modelId = $(this).attr("data-modelid");
                var input = $(this).parent().find('.txtReply-' + parentId).val();
                var txtComment = $.trim(input);
                if (txtComment != "") {
                    OwnerVoteCommentEvent.PostReplyComment(parentId, txtComment, brandId, modelId);
                    $(".txtReplyComment").val("");
                }
                else {
                    alert("Your comment field is empty");
                    $(this).prev().focus();
                }
            }
        });

        //showMoreSubComment
        $('#lsComment').on('click', '.loadmore-childcmt', function (e) {
            //skip douple click
            if (Utility.IsDoubleClicked($(this))) return;

            var idParent = $(this).data('id');
            var lastId = $(this).attr('data-lastid');
            OwnerVoteCommentEvent.getListCommentInfo(lastId * 1, idParent, 0, OwnerVoteCommentEvent.currentTab);
            //e.preventDefault();
        });

        //showMoreText
        $('#lsComment').on('click', '.show-more-text', function () {
            $(this).parent().hide();
            $(this).parent().next().show();
        });

        $('#lsComment').on('click', '.hide-more-text', function () {
            $(this).parent().prev().show();
            $(this).parent().hide();
        });

        //change color icon if have reply
        $("#lsComment .item-comtent").each(function (index) {
            if ($(this).find('#listCommentChild .list-acc').length > 0)
                $(this).find('.i-rely').css('color', '#2070D2');
        });
    },

    likeUnLike: function (index, islike) {
        var commentId = $(index).data("id");
        if (OwnerVoteCommentEvent.checkLogin()) {
            var count = parseInt($(index).find('.total_count').text());
            if (isNaN(count))
                count = 0;
            if ($(index).hasClass('active')) {
                if (count > 0)
                    count--;
                $(index).toggleClass('active');
            }
            else {
                // check unlike có class active không?
                if (islike == 1 && $(index).next().hasClass('active')) {
                    var unlikeCount = parseInt($(index).next().find('.total_count').text());
                    if (!isNaN(unlikeCount) && unlikeCount > 0)
                        $(index).next().find('.total_count').text(unlikeCount - 1);
                    $(index).next().removeClass('active');
                }
                else if ($(index).prev().hasClass('active')) {
                    // check like có class active không?
                    var likeCount = parseInt($(index).prev().find('.total_count').text());
                    if (!isNaN(likeCount) && likeCount > 0)
                        $(index).prev().find('.total_count').text(likeCount - 1);
                    $(index).prev().removeClass('active');
                }
                count++;
                $(index).toggleClass('active');
            }

            $(index).find('.total_count').text(count);

            var item = $(index).closest('.item-comtent');
            var brandId = $(item).attr("data-brandid");
            var modelId = $(item).attr("data-modelid");

            $.ajax({
                type: "POST",
                cache: false,
                url: "/OwnerReview/LikeUnLikeComment",
                data: ({
                    "commentId": commentId,
                    "status": islike,
                    "brandId": brandId,
                    "modelId": modelId
                }),
                success: function (response) {
                    if (response.Error) {
                        alert(response.Title);
                    }
                }
            });
        }
    },

    /**
     * Handler event owner review tab change
     * @param {any} tabIndex
     */
    reviewMenuChange(activeTab) {
        var tabIndex = $(activeTab).find("a").attr("tab-index") * 1;
        $(activeTab).find("a").addClass("active");
        //if content tab was loaded => show; else call server for load new
        var contentTab = $("#ctnContentTab-" + tabIndex);
        if (contentTab && contentTab.length > 0) {
            contentTab.show();
        } else {
            OwnerVoteCommentEvent.getListCommentInfo(0, 0, 0, tabIndex);
        }
        OwnerVoteCommentEvent.currentTab = tabIndex;
    },

    getListCommentInfo(id, parentid, numComment, tabIndex) {
        $.ajax({
            url: '/OwnerReview/GetListCommentReviewV2',
            data: {
                brandId: $("#hddBrandId").val(),
                modelId: $("#hddModel").val(),
                tabIndex: tabIndex,
                id: id,
                parentId: parentid,
                numComment: numComment,
                pageAll: $('.main-owner-review').length > 0
            },
            success: function (dataHtml) {
                if (parentid > 0) {
                    //Load subcomment tiep theo
                    $('#lst-comment-child-' + parentid).prepend(dataHtml).prepend(function () {
                        var loadmore = '#loadmore-' + parentid;
                        var loadmorechild = "#loadmore-childcmt-" + parentid;

                        if ($(loadmore).length > 0) {
                            var lastId = $(loadmore).attr('data-lastid');
                            $(loadmorechild).attr('data-lastid', lastId);
                            $(loadmore).remove();
                        } else {
                            $(loadmorechild).remove();
                        }
                    });
                } else {
                    $('#commentBoxContainer #lsComment').append(dataHtml);
                }
            }
        });

    },

    showMessageError() {
        let htmlError = `<div class="modal-alert in" id="popError" style="display: block;">
                                <div class="modal-dialog-alert">
                                    <div class="content-popup">
        	                            <span class="close"><i class="icon-cancel-5"></i></span>
        	                            <div class="box-owner-review-noti">
            	                            <img src="/ContentV2/Web/img/review-icon-1.png">
                                            <h3 class="title-noti">You haven't reviewed yet</h3>
                                            <p class="text-sub mb-20">Please select at least one review to submit</p>
                                            <button class="button-green w-250 btnCancel">BACK</button>
                                        </div>

   		                             </div>
                                </div>
                            </div>`;

        $('#popup').append(htmlError).show();
        CommonsEvent.AddNoScroll();
        $("#popError .close, #popError .btnCancel").on("click", function (e) {
            e.stopPropagation();
            $("#popError").remove();
        });
    },

    confirmCloseReview() {
        let htmlError = `<div class="modal-alert in" id="popQuit" style="display: block;">
                            <div class="modal-dialog-alert">
                                <div class="content-popup">
        	                        <span class="close"><i class="icon-cancel-5"></i></span>
        	                        <div class="box-owner-review-noti">
            	                        <img src="/ContentV2/Web/img/review-icon-2.png">
                                        <h3 class="title-noti">You haven't completed your review</h3>
                                        <p class="text-sub mb-20">All review will be erased. Do you want to quit?</p>
                                        <div class="row">
                                            <div class="col-6">
                    	                        <button class="button-green btnCancel">CANCEL</button>
                                            </div>
                                            <div class="col-6">
                    	                        <button class="button-gray btnOk">YES</button>
                                            </div>
                                        </div>
                                    </div>
   		                         </div>
                            </div>
                        </div>`;
        $('#popup').append(htmlError).show();
        CommonsEvent.AddNoScroll();
        $("#popQuit .close, #popQuit .btnCancel").on("click", function (e) {
            e.stopPropagation();
            $("#popQuit").remove();
        });
        $("#popQuit .btnOk").on("click", function (e) {
            OwnerVoteCommentEvent.dataChange = false;
            CommonsEvent.ClosePopup();
        });
    },

    showMessageSuccess() {
        let htmlSuccess = ` <div class="modal-alert in" id = "" style = "display: block;" >
                                <div class="modal-dialog-alert">
                                    <div class="content-popup">
        	                            <span class="close"><i class="icon-cancel-5"></i></span>
        	                            <div class="box-owner-review-noti">
            	                            <img src="/ContentV2/Web/img/icon-star.png">
                                            <h3 class="title-noti">Thanks for your review</h3>
                                            <p class="text-sub">
                                                Your comment is very important to others <br>who want to buy this car
                                            </p>
                                        </div>
   		                             </div>
                                </div>
                            </div>`;
        $('#popup').empty().html(htmlSuccess).show();
        CommonsEvent.AddNoScroll();
    }
};

$(document).ready(function () {
    OwnerVoteCommentEvent.init();
});
