if (!estimate) var estimate = {};
var es = estimate;

$(document).ready(function() {
    es.finalContent.init();
    es.finalModal.init();
    es.supply.init();

});

function comma (str) {
    str = String(str);
    return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
}
function uncomma(str) {
    str = String(str);
    return str.replace(/[^\d]+/g, '');
}

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

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

        $('.modelImg').on('click', function() {
            $selectedImg = $(this).children('img:eq(0)');
            oThis.selectedId = $selectedImg.data('couple-id');
            oThis.targetTableIdx = $(this).closest('table').index();
            es.finalModal.loadFavoriteCouple($selectedImg, oThis.selectedId);
        });
    },

    updateFinal: function(oldFinalId, newFinalId, finalFunction) {
        var oThis = this;
        $.ajax({
            url: '/order_contract/estimate/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;
                $('table:eq(' + oThis.targetTableIdx + ')').replaceWith(response);

                oThis.selectFinalCouple();
                es.supply.init();

                es.supply.updatePrice($('table:eq(' + oThis.targetTableIdx + ')'));

            }
        });
    },

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


es.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'));
            });

            es.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();


        var top = $(window).scrollTop() + 60;
        $('.ModelModalWrap').css({'top':top});
 
        $(".ModelModalWrap .closebtn").click(function(){
            oThis.closeModal();
        }); 
    },

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

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

es.supply = {
    $targetTable: null,
    targetCouple: null,
    verifiedUser: false,
    submitUrl: {
        'set': '/order_contract/estimate/set_discount_rate/',
        'option': '/order_contract/estimate/option_discount_rate/' 
    },

    initPopupEvent: function($target) {
        var oThis = this,
            $targetTable = $target.closest('table'),
            targetClass = $targetTable[0].className,
            updateSet = null,
            updateOption = null,
            currentItem = null,
            $coupleDiscountMenu = $(".menu-discount-couple"),
            $optionDiscountMenu = $(".menu-discount-option");

        if (targetClass === "estimate01T") {
            updateSet = $targetTable.data('final');
            currentItem = 'set';

            oThis.openMenu($target, $coupleDiscountMenu, currentItem);
            oThis.productSubmit($targetTable, updateSet, currentItem, $coupleDiscountMenu); 
        } else if (targetClass === "optionTable") {
            updateOption = $targetTable.data('option');
            currentItem = 'option';

            oThis.openMenu($target, $optionDiscountMenu, currentItem);
            oThis.optionSubmit($targetTable, updateOption, currentItem, $optionDiscountMenu);
        }
    },

    openPasswdModal: function($target) {
        var oThis = this;

        // 패스워드 모달창 현재 화면 가운데에 띄우기
        $(".ModalPW").css({
            "top":(($(window).height()-$(".ModalPW").outerHeight())/2+$(window).scrollTop())+"px",
        });  
        $(".ModalPW, .Modalmask").fadeIn();
        $(".ModalPWInput").val("");

        $(".ModalPWBtn").unbind().bind('click', function() {
            oThis.checkAccount($target);   
        });         
    },

    checkAccount: function($target) {
        var oThis = this,
            $inpPassword = $(".ModalPWInput");

        $.ajax({
                url: '/accounts/passwd_check/',
                type: 'POST',
                cache: false,
                data: {
                    'username': username,
                    'password': $inpPassword.val()
                },
                async: false,
                success: function(response) {
                    if (response.success == true) {
                        oThis.verifiedUser = true;
                        oThis.closePasswdModal();
                        oThis.initPopupEvent($target);
                    } else {
                        $inpPassword.val("");
                        $inpPassword.focus();
                        alert("비밀번호가 틀렸습니다.")
                    }
                }
            });
    },

    closePasswdModal: function() {
        $(".ModalPW, .Modalmask").fadeOut();
    },

    openMenu: function($target, $discountMenu, currentItem) {
        var tableheight = $target.offset().top;
        $discountMenu.siblings('.hello').fadeOut();

        $discountMenu.css('top',tableheight-25).fadeIn();
        $discountMenu.find('input:eq(0)').val($target.data("rate"));
        $discountMenu.find('input:eq(1)').val($target.data("acc-rate"));

        if (currentItem === 'set') {
            var $accMenu = $discountMenu.find('.menu-discount-acc')
            if ($target.closest('table').find('.row-acc').length === 0) {
                $accMenu.hide();
            } else {
                $accMenu.show();
            }
        }
    },

    checkValidData: function($input, max_rate) {
        var regInt = /^[0-9]+$/,
            returnData = true;

        $.each($input, function(idx) {
            rate = $(this).val();

            if (!regInt.test(rate) || (rate > 100)) {
                $(this).focus();
                $.alert({title: '알림', content: "0 이상 100 이하의 정수로 입력해주세요.", useBootstrap: false});
                returnData = false;
                return false;
            }

            if (idx > 0) {
                max_rate = 100;
            } 

            if (rate > max_rate) {
                $(this).focus();
                $.alert({title: '알림', content: "죄송합니다. 공급불가 가격입니다.", useBootstrap: false});
                returnData = false;
                return false;
            }
        });
        return returnData;

    },

    productSubmit: function($table, data, currentItem, $discountMenu) {
        var oThis = this,
            productRate = 0,
            accRate = 0,
            regInt = /^[0-9]+$/,
            max_rate = $table.find('th:eq(3)').data('max'),
            $input = $discountMenu.find('input'),
            $productRow = null,
            $accRow = null;

        $(".helloSubmit").unbind().bind('click', function(e){      
            if (!oThis.checkValidData($input, max_rate)) {
                return false;
            } 

            $(".hello").fadeOut();
            productRate = $("#inp-discount-product").val();
            accRate = $("#inp-discount-acc").val() ;

            $.ajax({
                url: oThis.submitUrl[currentItem],
                type: 'POST',
                cache: false,
                data: {
                    'orderId': order_id,
                    'updateId': data,
                    'rate': productRate,
                    'acc_rate': accRate 
                },
                async: false,
                success: function(response) {
                    $table.find('th:eq(3)').data({
                        'rate': productRate,
                        'acc-rate': accRate
                    });

                    oThis.updatePrice($table);
                }
            });
        });
    },

    updatePrice: function ($table) {
        var $productRow = $table.find('tr:gt(0)').not('.row-acc'),
            $optionRow = $table.find('.row-acc'),
            productRate = $table.find('th:eq(3)').data('rate'),
            accRate = $table.find('th:eq(3)').data('acc-rate');

        this.setSupplyPrice($productRow, productRate);
        this.setSupplyPrice($optionRow, accRate);
        this.setTotalPrice($table);
    },

    optionSubmit: function($table, data, currentItem, $discountMenu) {
        var oThis = this,
            rate = null,
            regInt = /^[0-9]+$/,
            max_rate = $table.find('th:eq(3)').data('max'),
            $input = $discountMenu.children('input');

        $(".helloSubmit").unbind().bind('click', function(e){    
            if (!oThis.checkValidData($input, max_rate)) {
                return false;
            } 
            rate = $input.val();

            $(".hello").fadeOut();

            $.ajax({
                url: oThis.submitUrl[currentItem],
                type: 'POST',
                cache: false,
                data: {
                    'orderId': order_id,
                    'updateId': data,
                    'rate': rate
                },
                async: false,
                success: function(response) {
                    $table.find('th:eq(3)').data('rate', rate);
                    
                    var $updateRow = $table.find('tr:gt(0)');
                    oThis.setSupplyPrice($updateRow, rate);
                }
            });
        });
    },
    
    setSupplyPrice: function($row, rate) {
        var tagPriceText = null,
            tagPrice = 0,
            discountPriceText = null,
            discountPrice = 0;

        $.each($row.not('.total-boy, .total-girl'), function() {
            if ($(this).find('td').eq(1).text() === "") {
                return false; 
            }

            tagPriceText = $(this).find('td').eq(2).text();
            tagPrice = parseInt(uncomma(tagPriceText.split("원")[0]));

            if (parseInt(rate) === 0) {
                discountPrice = tagPrice;    
            } else {
                discountPrice = Math.ceil((tagPrice - tagPrice * (rate * 0.01)) / 100) * 100;
            }

            discountPriceText = comma(discountPrice) + "원";
            $(this).find('td').eq(3).text(discountPriceText);
        });
    },

    setTotalPrice: function($table) {
        var totalTagPrice = 0,
            totalDiscountPrice = 0,
            girlTotalTagPrice = 0,
            girlTotalDiscountPrice = 0,
            boyTotalTagPrice = 0,
            boyTotalDiscountPrice = 0,
            tagPriceText = null,
            discountPriceText = null;

        $.each($table.find('tr:gt(0)').not(':last, .total-boy,  .total-girl'), function () {
            if ($(this).children('td:eq(0)').text() === '') {
                return false;
            }

            if ($(this).children('td:eq(1)').text().indexOf('남아') > 0) {
                boyTotalTagPrice += parseInt(uncomma($(this).children('td:eq(2)').text().split("원")[0]));
                boyTotalDiscountPrice += parseInt(uncomma($(this).children('td:eq(3)').text().split("원")[0]));
            } else if ($(this).children('td:eq(1)').text().indexOf('여아') > 0) {
                girlTotalTagPrice += parseInt(uncomma($(this).children('td:eq(2)').text().split("원")[0]));
                girlTotalDiscountPrice += parseInt(uncomma($(this).children('td:eq(3)').text().split("원")[0]));
            }
        });
        $table.find('tr.total-boy').children('td:eq(2)').text(comma(boyTotalTagPrice) + "원");
        $table.find('tr.total-boy').children('td:eq(3)').text(comma(boyTotalDiscountPrice) + "원");

        $table.find('tr.total-girl').children('td:eq(2)').text(comma(girlTotalTagPrice) + "원");
        $table.find('tr.total-girl').children('td:eq(3)').text(comma(girlTotalDiscountPrice) + "원");

        $table.find('tr:last-child').children('td:eq(2)').text(comma(boyTotalTagPrice + girlTotalTagPrice) + "원");
        $table.find('tr:last-child').children('td:eq(3)').text(comma(boyTotalDiscountPrice + girlTotalDiscountPrice) + "원");
    },

    initSetSupplyPrice: function() {
        var oThis = this,
            productRate = null,
            accRate = null,
            optionRate = null,
            $productRow = null,
            $accRow = null,
            $optionRow = null;

        $.each($(".estimate01T"), function() {
            productRate = $(this).find('th:eq(3)').data('rate');
            accRate = $(this).find('th:eq(3)').data('acc-rate');
            
            $productRow = $(this).find('tr:gt(0)').not('.row-acc');
            $optionRow = $(this).find('.row-acc');
            
            oThis.setSupplyPrice($productRow, productRate);
            oThis.setSupplyPrice($optionRow, accRate);
            oThis.setTotalPrice($(this));
        });

        $.each($('.optionTable'), function() {
            optionRate = $(this).find('th:eq(3)').data('rate');
                    
            var $optionRow = $(this).find('tr:gt(0)');
            oThis.setSupplyPrice($optionRow, optionRate);
        });   
    },

    init: function() {
        var oThis = this;
        this.initSetSupplyPrice();
        
        $("table").find("th:eq(3)").unbind().bind('click', function(){
            if (!(oThis.verifiedUser)) {
                oThis.openPasswdModal($(this));
            } else {
                oThis.initPopupEvent($(this));
            }
        });
        $(".ModalPW").children('.closebtn').on('click', function() {
            oThis.closePasswdModal();
        });
    }
};