
var mail = {
    init: function() {
        var oThis = this;
        $("#sendMailBtn").on('click', function() {
            oThis.openModal();
        });
        $(".mailMenuClose").on('click', function() {
            oThis.closeModal();
        });
        $("#submitBtn").on('click', function(e) {
            e.stopImmediatePropagation();
            oThis.submit();
        });
        $(".addMail").on('click', function(e) {
            e.stopImmediatePropagation();
            oThis.addEmailAddress();
        });
        $(".block-inp").find('select[name=sel-email]').on('change', function() {
            oThis.selectDomain($(this));
        });
    },
    openModal: function() {
        $(".mailModalWrap").css({
            "top":(($(window).height()-$(".mailModalWrap").outerHeight())/2+$(window).scrollTop())+"px",
        })
        $(".mailModalBack, .mailModalWrap").fadeIn(); 
    },
    closeModal: function() {
        $(".mailModalBack, .mailModalWrap").fadeOut();
    },
    selectDomain: function($select) {
        var domain = $select.val(),
            $inpDomain = $select.closest('li').find("input[name='mail-domain']");

        if (domain === 'none') {
            $inpDomain.val("");
            $inpDomain.attr('disabled', false);
        } else {
            $inpDomain.val(domain);
            $inpDomain.attr('disabled', true);
        }
    },
    submit: function() {
        var oThis = this,
            $emailElements = $(".block-inp").children('li').not('.addMail'),
            emailList = [],
            $email = null,
            account = null,
            domail = null,
            returnVal = true;
        
        $.each($emailElements, function() { 
            $email = $(this);
            account = $email.find('input[name=mail-account]').val();
            domain = $email.find('input[name=mail-domain]').val();

            if (account === "" || domain === "") {
                return;
            } else {
                emailList.push(account + '@' + domain);
            }

            if (oThis.checkDomain(domain) === false) {
                returnVal = false;
                $.alert({title: '알림', content: "도메일 형식이 올바르지 않습니다.", useBootstrap: false});
                $email.find('input[name=mail-domain]').focus();
                return false;
            }
        });

        if (returnVal === false) {
            return false;
        }
        if (emailList.length === 0) {
            $.alert({title: '알림', content: "1개 이상의 이메일 주소를 입력해주세요.", useBootstrap: false});
            return false;
        }

        $.ajax({
            type: 'POST',
            url: '/order_contract/send_mail/',
            data: {
                'order_id': order_id,
                'email': emailList
            },
            beforeSend: function() {
                var offset = $('.mailModalWrap').offset();
                $('.overlay').css({
                    'top': offset.top,
                    'height': $('.mailModalWrap').height()
                })
                .show();
            },
            complete: function() {
                $('.overlay').hide();
            },
            success: function() {
                $.alert({title: '알림', content: "발송이 완료되었습니다.", useBootstrap: false});
                oThis.closeModal();
            }
        }); 
    },
    checkDomain: function(domain) {
        var reg = /\S+\.\S+/;
        return reg.test(domain);
    },
    addEmailAddress: function() {
        var addressLength = $(".block-inp > li").not('.addMail').length;
        $(".addMail").before(
            "<li>\
                <label for='inp-mail-to" + parseInt(addressLength + 1) + "'>To :</label>\
                <input type='text' autocapitalize='off' id='inp-mail-to" + parseInt(addressLength + 1) + "' name='mail-account'>@\
                <input type='text' autocapitalize='off' name='mail-domain'>\
                <select name='sel-email'>\
                    <option value='none'>직접입력</option>\
                    <option value='naver.com'>naver.com</option>\
                    <option value='hanmail.net'>hanmail.net</option>\
                    <option value='gmail.com'>gmail.com</option>\
                    <option value='nate.com'>nate.com</option>\
                </select>\
            </li>"
        );
        this.init();
    }
};

function mailModalBackHeight() {
    var winheight = $("html").height();
    $(".mailModalBack").css('height',winheight);
}
mailModalBackHeight();


function makePdf() {
    var pdfFile,
        $elements = $('.a4SizeWrap'),
        content = [],
        count = 0;
        docDefinition = {content: content};

    for (i = $elements.length - 1; i >= 0; i--) {
        makeCanvas(i); 
    } 

    function makeCanvas(idx) {
        count += 1;
        html2canvas($elements[idx], {
            onrendered: function(canvas) {
                var data = canvas.toDataURL(); 
                content[idx] = {
                    image:data, 
                    width:520,
                    margin: [0,20]
                };
                count -= 1;
                if (count === 0) {
                    pdfMake.createPdf(docDefinition).getDataUrl(function(dataUrl) {
                        var pdfFile = dataUrl;
                        $.ajax({
                            type: 'POST',
                            url: '/order_contract/pamphlet/pdf/save/',
                            data: {
                                'order_id': order_id,
                                'pdf_file': pdfFile
                            },
                            async: false,
                            success: function() {

                            }
                        }); 
                    });
                }
            }
        })
    }
}

$(document).ready(function() {
    mail.init();
    makePdf();
});