if (!option) var option = {};
var op = option;

$(document).ready(function() {
    op.finalContent.init();
    op.finalModal.init();
    op.finalOption.init();


});

op.finalContent = {
    selectedId: null,
    cacheSet: {},
    isFront: true,

    selectFinalCouple: function() {
        var oThis = this,
            $selectedImg = null;

        oThis.rotate();
        $(".modelWrap").children('.modelImg').on('click', function() {
            $selectedImg = $(this).children('.front').find('.final-model');
            oThis.selectedId = $selectedImg.data('couple-id');
            op.finalModal.loadFavoriteCouple($selectedImg, oThis.selectedId);
            
        });
    },

    updateFinal: function(oldFinalId, newFinalId, finalFunction) {
        var oThis = this;
        $.ajax({
            url: '/order_contract/add_option/update_final/',
            type: 'POST',
            cache: false,
            data: {
                'order_id': order_id,
                'oldId': oldFinalId,
                'newId': newFinalId,
                'finalFunction': finalFunction
            },
            async: false,
            success: function (response) {
                oThis.selectedId = newFinalId;

                $('.modelWrap').html('').append(response);
                oThis.selectFinalCouple();
            }
        });
    },

    bindRotate: function() {
        var oThis = this;
        $(".rotate_btn").on('click', function() {
            if (oThis.isFront === true) {
                oThis.isFront = false;
            } else {
                oThis.isFront = true;
            }
            oThis.rotate();
        });
    },

    rotate: function() {
        if (this.isFront) {
            $.each($(".modelImg"), function() {
                $(this).find('.front').show().siblings().hide();
            });
        } else {
            $.each($(".modelImg"), function() {
                $(this).find('.back').show().siblings().hide();
            });
        }
    },

    init: function() {
        this.selectFinalCouple();
        this.bindRotate();
        this.rotate();
    }
};


op.finalModal = {
    loadFavoriteCouple: function($target, selectedFinalId) {
        var oThis = this;
        this.openModal();
        $.ajax({
            url: '/order_contract/add_option/favorite_set_list/',
            type: 'POST',
            cache: false,
            data: {
                'orderId': order_id,
                'coupleId': selectedFinalId
            },
            async: false,
            success: function(response) {
                $('.favoriteContent').html('');
                $('.mainModelWrap').html('');
                
                // 기존 선택 이미지
                $target.clone().appendTo('.mainModelWrap');

                // 관심 선택 이미지
                $(".favoriteContent").append(response);

                oThis.selectFavoriteCouple();
                oThis.selectFunction();

                oThis.changeFinalCouple(selectedFinalId);
            }
        });
    },

    selectFavoriteCouple: function () {      
        var newImg = null,
            oldImg = null;

        $(".favorite-couple-list").find('li').on('click', function() {
            newImg = $(this).children('img');
            oldImg = $('.mainModelWrap').children('img');

            newImg.clone().appendTo($('.mainModelWrap').html(''));
            oldImg.clone().appendTo($(this).html(''));
        });
    },

    changeFinalCouple: function(selectedFinalId) {
        var oThis = this;

        $(".ModalSaveBtn").click(function() {
            var newSelectedId = $('.mainModelWrap').children('img').data('couple-id'),
                selectedFunction = [];

            $.each($('.accIcon').children('li.active'), function() {
                selectedFunction.push($(this).data('function-id'));
            });

            op.finalContent.updateFinal(selectedFinalId, newSelectedId, selectedFunction);
            oThis.closeModal();
        });
    },

    selectFunction: function() {
        var oThis = this,
            $items = $(".accIcon").children('li').not('.default');

        $items.on('click', function() {
            $(this).toggleClass('active');
        });
    },

    openModal: function() {
        var oThis = this;
        $(".Modalmask").fadeIn();
        $(".ModelModalWrap").fadeIn();
        $(".ModelModalWrap .closebtn").click(function(){
            oThis.closeModal();
        }); 
    },

    closeModal: function() {
        $(".Modalmask").fadeOut();
        $(".ModelModalWrap").fadeOut();
    },

    init: function() {
        this.closeModal();
        this.selectFunction();
        this.changeFinalCouple();
    }
};


op.finalOption = {
    $selectMainCategory: null,
    option_list: [],
    selectedOption: null,

    selectMainCategory: function () {
        var oThis = this;
        $(".contentTab").children('li').on('click', function () {

            oThis.getSubCategory($(this));
        });
    },

    selectMainCategoryIndex: function (index) {
        var oThis = this,
            $target = $(".contentTab").children('li').eq(index);

        this.getSubCategory($target);
    },

    getSubCategory: function ($mainCategory) {
        var oThis = this;

        $("ul.contentTab li").removeClass("active");
        $mainCategory.addClass("active");

        $.ajax({
            url: '/order_contract/add_option/option_sub_category/',
            type: 'POST',
            data: {
                mainCId: $mainCategory.data('option-id')
            },
            async: false,
            success: function (response) {
                $(".innerTab").html('').append(response);     
                oThis.selectSubCategory();
                oThis.selectSubCategoryIndex(0);
            }
        });
    },

    selectSubCategory: function() {
        var oThis = this;
        $(".innerTab").children('li').on('click', function() {
            oThis.getOptionItemList($(this));
        });
    },

    selectSubCategoryIndex: function(index) {
        var oThis = this,
            $target = $(".innerTab").children('li').eq(index);

        this.getOptionItemList($target);
    },

    getOptionItemList: function($subCategory) {
        var oThis = this;

        $("ul.innerTab li").removeClass("active");
        $subCategory.addClass("active");

        $.ajax({
            url: '/order_contract/add_option/option_list/',
            type: 'POST',
            data: {
                order_id: order_id,
                subCId: $subCategory.data('option-id')
            },
            async: false,
            success: function (response) {
                $(".etcTab").hide().html('').append(response).fadeIn('fast');
                oThis.selectedOption = null;

                if ($('.etcTab').find('.active').length !== 0) {
                    oThis.selectedOption = $(".etcTab").find('.active').data('option');
                }
                oThis.selectOption();

                slimScroll();
            }
        });
    },

    selectOption: function() {
        var oThis = this;
        $('.etcTab').children('li').on('click', function() {
            // active 상태의 option item이 있을 경우 먼저 선택했던 item을 삭제
            if (oThis.selectedOption !== null) {
                oThis.removeOptionItem(oThis.selectedOption);

                // active 상태인 option item을 click
                if (oThis.selectedOption === $(this).data('option')) {
                    oThis.selectedOption = null;
                    return false;
                }
            }
            
            $(this).addClass('active');

            oThis.selectedOption = $(this).data('option');
            oThis.addOptionItem(oThis.selectedOption);
        });   
    },

    removeOptionItem: function(optionId) {
        var oThis = this;

        $('.etcTab').find('[data-option=' + optionId + "]").removeClass('active');

        $.ajax({
            url: '/order_contract/add_option/delete_option_item/',
            type: 'post',
            data: {
                order_id: order_id,
                optionId: optionId
            },
            success: function(response) {
                if (response) {
                    $(".modelImg").children('p').find('[data-option=' + optionId + ']').remove();
                }
            }
        });
    },

    addOptionItem: function(optionId) {
        var removeOptionId = null,
            optionFront = null,
            optionBack = null;
        $.ajax({
            url: '/order_contract/add_option/add_option_item/',
            type: 'post',
            data: {
                order_id: order_id,
                optionId: optionId
            },
            success: function(response) {
                optionFront = response.front;
                optionBack = response.back;

                $(".modelImg").find('.front').append(
                    $("<img />").attr({
                        'src': optionFront,
                        'data-option': optionId
                    })
                );
                $(".modelImg").find('.back').append(
                    $("<img />").attr({
                        'src': optionBack,
                        'data-option': optionId
                    })
                );
            }
        });
    },

    init: function() {
        this.selectMainCategory();
        this.selectMainCategoryIndex(0);
    }
};

