/* 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 '='
(587,1): run-time error CSS1019: Unexpected token, found '$'
(587,2): run-time error CSS1019: Unexpected token, found '('
(587,11): run-time error CSS1031: Expected selector, found ')'
(587,11): run-time error CSS1025: Expected comma or open brace, found ')'
(589,2): run-time error CSS1019: Unexpected token, found ')'
 */
var OwnerVoteCommentEvent = {
    init: function () {
        if ($('#hddBrandId').length == 0)
            return;

        if ($('#hddModel').length == 0)
            return;

        if ($(".pg-carguide-detail").length > 0) {
            this.initEvent();
        } else {
            this.initUI();
        }

        if ($('#owner-review-filter').length > 0) {
            this.initUI(); //generate owner review
            this.initPageListEvent();
        }

        //Load page review detail
        if ($('#commentBoxContainer').length) {
            OwnerVoteCommentEvent.getListCommentInfo(0, 0, 0);
        }
    },

    initUI: function (brandId, modelId) {

        if (typeof brandId == 'undefined')
            brandId = $("#hddBrandId").val();

        if (typeof modelId == 'undefined')
            modelId = $("#hddModel").val();

        var dataType = 'application/json; charset=utf-8';
        var data = {
            BrandId: brandId,
            ModelId: modelId,
            pageDetail: $(".pg-carguide-detail").length > 0,
            showCarGuide: $("#owner-review-filter").length > 0,
        }

        $.ajax({
            type: "POST",
            cache: false,
            url: '/OwnerReview/CommentOwnerInfo',
            contentType: dataType,
            data: JSON.stringify(data),
            success: function (dataHtml) {
                if (!dataHtml.Error && !!dataHtml && dataHtml.indexOf('<head>') == -1) {
                    $('#comment-owner-info').empty().html(dataHtml).append(function () {
                        OwnerVoteCommentEvent.initEvent();

                        if ($('#owner-review-title').length > 0 && $('#hddCarInfoYear').length > 0)
                            $('#owner-review-title').text($('#hddCarInfoYear').val());

                        if ($('#btnSubmitOwnerVote').length == 0) {
                            $('.carguide-review-content').addClass('read');
                            $('.carguide-review-content textarea').prop('readonly', true);
                        }
                    });
                }
            }
        });
    },

    initEvent: function () {
        //OwnerVoteCommentEvent.initEventKeyUp();

        //Set star trong vote
        $('.voteOwner .voting').mouseover(function () {
            if ($('#btnSubmitOwnerVote').length) {
                var ratePoint = parseFloat($(this).data("rate"));
                var voteOwner = $(this).parent().closest(".voteOwner");
                OwnerVoteCommentEvent.activeRate(voteOwner, ratePoint);
            }
        }).click(function () {
            if ($('#btnSubmitOwnerVote').length && OwnerVoteCommentEvent.checkLogin()) {
                var ratePoint = parseFloat($(this).data("rate"));
                var voteOwner = $(this).parent().closest(".voteOwner");
                OwnerVoteCommentEvent.activeRate(voteOwner, ratePoint);
                voteOwner.attr("data-value", ratePoint);
            }
        }).mouseout(function () {
            if ($('#btnSubmitOwnerVote').length) {
                var voteOwner = $(this).parent().closest(".voteOwner");
                var ratePoint = parseFloat(voteOwner.attr("data-value"));
                OwnerVoteCommentEvent.activeRate(voteOwner, ratePoint);
            }
        });

        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) {
                    $(this).parent().parent().find(".txtarea").removeClass("hide").focus();
                    $(this).closest(".box-vote").addClass("heading-toprating");
                    $(this).hide();
                }
            }
        });

        $('.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();
            }
        }
    },

    initContentOwner: function () {
        $(".voteOwner").each(function (index, value) {
            if ($(value).attr('data-value') > 0) {
                OwnerVoteCommentEvent.activeRate($(this), $(value).attr('data-value'));
            }
        })

        $(".elm_right").each(function (index, value) {
            var textarea = $(value).find("textarea");
            if (textarea.val() != "") {
                textarea.removeClass("hide");
                $(value).find(".box-vote").addClass("heading-toprating");
                $(value).find(".btn-edit").hide();
            }
        })
    },

    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;
            }

            if (OwnerVoteCommentEvent.checkLogin()) {
                if (!OwnerVoteCommentEvent.checkValidVote()) {
                    return false;
                }

                if (!OwnerVoteCommentEvent.checkValidRating()) {
                    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();
                            var message = "You review has been posted successfully. Thank you for using our service!";
                            //var note = "*Note: At the end of Car of the week campaign, a lucky owner who contributed one or more reviews will be rewarded. Please update your phone number or email so we can contact if you win.";

                            if (typeof MsgBox != 'undefined') {
                                MsgBox.MessageSuccessWithDescription(message, '', "popup-carguide-review");
                            } else {
                                MessageSuccessWithDescription(message, '', "popup-carguide-review");
                            }

                            $('#lsComment').prepend(response.Obj);
                        }
                    }
                });
            }
        });
    },

    //Click comment, chua login thi show form login
    initEventKeyUp: function () {
        $('.txtarea').on("click", function () {
            OwnerVoteCommentEvent.checkLogin();
            return;
        });
    },

    activeRate: function (voteOwner, rateint) {
        if (isNaN(rateint))
            return false;
        voteOwner.find('i').each(function () {
            var rating = $(this).find('span:first-child').data("rate");
            if (rating == rateint) {
                $(this).attr("class", "i_star_half");
            }
            else if (rating <= rateint) {
                $(this).attr("class", "i_star");
            }
            else
                $(this).attr("class", "i_star_outline");
        });
    },

    checkValidVote() {
        var result = true;
        var checkRate = false;
        $(".voteOwner").each(function (index, value) {
            if ($(value).attr('data-value') > 0) {
                checkRate = true;
                $(value).parent().find(".btn-edit").click();
                var textarea = $(value).parent().parent().find("textarea");
                if (textarea.val() == "") {
                    alert(textarea.attr("placeholder"));
                    textarea.focus();
                    result = false;
                    return result;
                }
            }
        })

        if (!checkRate) {
            alert("Please rate your experience on one of the following criteria");
            result = false;
            return result;
        }

        return result;
    },

    checkValidRating() {
        var result = true;
        $(".voteOwner").each(function (index, value) {
            var textarea = $(value).parent().parent().find("textarea");
            if (textarea.val() != "") {
                if ($(value).attr('data-value') == 0) {
                    alert("You need to give rating if you give your review");
                    result = false;
                    return result;
                }
            }
        })

        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,
        }

        $.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");
                }
            }
        });
    },

    //Page comment
    getListCommentInfo(id, parentid, numComment) {
        if ($('#commentBoxContainer').length) {
            $.ajax({
                url: '/OwnerReview/GetListCommentReview',
                data: {
                    brandId: $("#hddBrandId").val(),
                    modelId: $("#hddModel").val(),
                    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 if (id > 0) {
                        //Load comment tiep theo
                        $(".btn-loadmore").remove();
                        $('#commentBoxContainer #lsComment').append(dataHtml);
                    }
                    else {
                        //Load comment and list comment ban dau
                        $('#commentBoxContainer #lsComment').empty().html(dataHtml).append(function () {
                            OwnerVoteCommentEvent.initCommentDetail();
                        });
                    }
                }
            });
        }
    },

    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 = $('.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();
                }
            }
        });

        this.showMoreComment();
        this.showMoreSubComment();
        this.showMoreText();

        //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);
                    }
                }
            });
        }
    },

    showMoreComment: function () {
        $('#lsComment').on('click', '.btn-loadmore', function (e) {
            var lastId = $(this).attr('data-lastid');
            var numComment = $(this).attr('data-numcomment');
            e.preventDefault();
            OwnerVoteCommentEvent.getListCommentInfo(lastId, 0, numComment);
        });
    },

    showMoreSubComment: function () {
        $('#lsComment').on('click', '.loadmore-childcmt', function (e) {
            var idParent = $(this).data('id');
            var lastId = $(this).attr('data-lastid');
            OwnerVoteCommentEvent.getListCommentInfo(lastId, idParent, 0);
            e.preventDefault();
        });
    },

    showMoreText: function () {
        $('#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();
        });
    },

    //page list
    initPageListEvent: function () {
        var box = '#owner-review-filter';

        var brandId = $('#hddBrandId').val();
        var modelId = $('#hddModel').val();
        $('#cboBrand', box).val(brandId).trigger("chosen:updated");
        //$('#cboModel', box).val(modelId).trigger("chosen:updated");

        this.generateModel(brandId, modelId);

        $('#cboBrand', box).change(function () {
            brandId = parseInt($('#cboBrand', box).val());
            OwnerVoteCommentEvent.generateModel(brandId);
        });

        $('#btnSearchFilter', box).on('click', function () {
            brandId = parseInt($('#cboBrand', box).val());
            if (brandId == 0) {
                alert('You must select a brand');
                return;
            }

            modelId = parseInt($('#cboModel', box).val());
            if (modelId == 0) {
                alert('You must select a model');
                return;
            }

            $('#hddBrandId').val(brandId);
            $('#hddModel').val(modelId);

            OwnerVoteCommentEvent.initUI(brandId, modelId);

        });

    },

    generateModel: function (brandId, modelId) {
        if (typeof modelId == 'undefined') modelId = 0;

        var jsonModel = null;
        if ($("body").data('GetListModel_' + brandId) != null) {
            jsonModel = $("body").data('GetListModel_' + brandId);
        }
        if (jsonModel == null) {
            $.ajax({
                type: "POST",
                cache: false,
                url: "/OwnerReview/GetListModelsHasCarGuideByBrandId",
                data: { "brandId": brandId },
                success: function (dataJson) {
                    jsonModel = dataJson;
                    $("body").data('GetListModel_' + brandId, jsonModel);
                },
                timeout: 5000,
                complete: function () {
                    OwnerVoteCommentEvent.bindModel(modelId, jsonModel);
                },
                error: function (request, status, error) {
                    //alert(request.responseText);            
                }
            });
        }
        else {
            OwnerVoteCommentEvent.bindModel(modelId, jsonModel);
        }
    },

    bindModel: function (modelId, jsonModel) {
        var box = '#owner-review-filter';
        $("#cboModel", box).find("option:gt(0)").remove();
        var strModel = $('#cboModel', box).html();
        if (jsonModel != undefined)
            $.each(jsonModel, function (index, objModel) {
                if (modelId == objModel.ModelId) {
                    strModel += '<option value="' + objModel.ModelId + '" selected="selected">' + objModel.ModelName + '</option>';
                }
                else {
                    strModel += '<option value="' + objModel.ModelId + '">' + objModel.ModelName + '</option>';
                }
            });
        $("#cboModel", box).html(strModel).trigger("chosen:updated");
    },
};

$(document).ready(function () {
    OwnerVoteCommentEvent.init();
});
