$(function() {

    function getDate(element) {
        var date;
        try {
            date = $.datepicker.parseDate(dateFormat, element.value);
        } catch (error) {
            date = null;
        }

        return date;
    }


    $(document).on({
        change: function() {
            if ($('.step_wrap').data('step') == '1') {

            }
            $.ajax({
                url: "/tpl/cart/booking_step.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&step=' + $('.step_wrap').data('step') + '&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort'),
                dataType: 'html',
                success: function(responseHtml) {
                    $('.booking-wrap').html(responseHtml);

                    if ($('.step_wrap').data('step') == '1') {
                        tripSrhDt();
                    }
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }

    }, '.srh_date');

    $(document).on({
        click: function() {
            if ($('.step_wrap').data('step') == '1') {

            }

            var newFdate = $('#from').datepicker('getDate');
            var newTdate = $('#to').datepicker('getDate');
            newFdate.setDate(newFdate.getDate() + 7);
            newTdate.setDate(newTdate.getDate() + 7);

            $('#from').datepicker('setDate', newFdate);
            $('#to').datepicker('setDate', newTdate);
            console.log($('#from').val() + ' ~ ' + $('#to').val());
            $.ajax({
                url: "/tpl/cart/booking_step.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&act=period-next&step=' + $('.step_wrap').data('step') + '&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort'),
                dataType: 'html',
                success: function(responseHtml) {
                    $('.booking-wrap').html(responseHtml);

                    if ($('.step_wrap').data('step') == '1') {
                        tripSrhDt();
                    }
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }

    }, '.period-next');

    $(document).on({
        click: function() {
            if ($('.step_wrap').data('step') == '1') {

            }

            var newFdate = $('#from').datepicker('getDate');
            var newTdate = $('#to').datepicker('getDate');
            newFdate.setDate(newFdate.getDate() - 7);
            newTdate.setDate(newTdate.getDate() - 7);

            $('#from').datepicker('setDate', newFdate);
            $('#to').datepicker('setDate', newTdate);

            $.ajax({
                url: "/tpl/cart/booking_step.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&act=period-prev&step=' + $('.step_wrap').data('step') + '&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort'),
                dataType: 'html',
                success: function(responseHtml) {
                    $('.booking-wrap').html(responseHtml);

                    if ($('.step_wrap').data('step') == '1') {
                        tripSrhDt();
                    }
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }

    }, '.period-prev');


    $(document).on({
        click: function() {
            if ($('.step_wrap').data('step') == '1') {

            }

            $(this).parents('.categories-block').find('.cat-button').text($(this).text());

            $('.trip-sel-wrap .cat-item.active').removeClass('active');
            $(this).addClass('active');

            $.ajax({
                url: "/tpl/cart/booking_step.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&step=' + $('.step_wrap').data('step') + '&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort'),
                dataType: 'html',
                success: function(responseHtml) {
                    $('.booking-wrap').html(responseHtml);

                    if ($('.step_wrap').data('step') == '1') {
                        tripSrhDt();
                    }
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }

    }, '.trip-sel-wrap .cat-item');


    $(document).on({
        click: function() {
            if ($('.step_wrap').data('step') == '1') {

            }

            $(this).parents('.categories-block').find('.cat-button').text($(this).text());

            $('.trip-sel-list .cat-item.active').removeClass('active');
            $(this).addClass('active');

            $.ajax({
                url: "/tpl/cart/new/booking_step.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&step=1&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort'),
                dataType: 'html',
                success: function(responseHtml) {
                    $('.booking-wrap').html(responseHtml);

                    // if ($('.step_wrap').data('step') == '1') {
                    //     tripSrhDt();
                    // }
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }

    }, '.trip-sel-list .cat-item');

    $(document).on({
        click: function() {
            if ($('.step_wrap').data('step') == '1') {

            }
            $.ajax({
                url: "/tpl/cart/booking_step.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&step=2&bookInfo=' + JSON.stringify($(this).data('book')),
                dataType: 'html',
                success: function(responseHtml) {
                    $('.booking-wrap').html(responseHtml);

                    if ($('.step_wrap').data('step') == '1') {
                        tripSrhDt();
                    }


                    if ($('.step_wrap').data('step') == '2') {
                        var minYr = -1;
                        $.each($(this).parents('.step_wrap').eq(0).data('calc'), function(idx, val) {
                            if (val['AgeMin'] == null) {
                                minYr = 0;
                            } else {
                                if ((minYr == -1) || (parseInt(minYr) >= parseInt(val['AgeMin']))) {
                                    console.log(val['AgeMin']);
                                    minYr = val['AgeMin'];
                                }
                            }
                        });
                        console.log('最小' + minYr);


                        $('.birth-picker').datepicker({
                            dateFormat: "yy/mm/dd",
                            yearRange: "-100:+0",
                            maxDate: -1 * minYr * 365,
                            //maxDate: "+0D",
                            changeYear: true,
                            changeMonth: true
                        }).on("change", function() {
                            var stepWrap = $(this).parents('.step_wrap').eq(0);
                            var tourlistAge = calculateAge($(this).val(), $(stepWrap).data('info')['date']);
                            var dtRow = $(this).parents('.torist-info-row').eq(0);
                            $(dtRow).find('.tourist-age').data('val', tourlistAge).children('span').text(tourlistAge);

                            var tourlistPrc = 0;
                            //console.log($(stepWrap).data('calc'));
                            $.each($(stepWrap).data('calc'), function(idx, val) {
                                console.log(idx + ' => ' + val['AgeMin'] + ' => ' + val['AgeMax'] + ' => ' + val['Price'] + ' => ' + val['memo']);
                                if (!val['AgeMin']) {
                                    if (tourlistAge <= val['AgeMax']) {
                                        tourlistPrc = val['Price'];
                                    }
                                } else if (!val['AgeMax']) {
                                    if (tourlistAge >= val['AgeMin']) {
                                        tourlistPrc = val['Price'];
                                    }
                                } else {
                                    if ((tourlistAge >= val['AgeMin']) && (tourlistAge <= val['AgeMax'])) {
                                        tourlistPrc = val['Price'];
                                    }
                                }
                            });

                            $(dtRow).find('.tourist-prc').data('val', tourlistPrc).children('span').text(tourlistPrc);
                            //$(dtRow).find('.tourist-prc').data('val',tourlistPrc);
                            calcTripSum();
                        });

                        $('.birth-picker').each(function(idx, elem) {
                            $(elem).trigger('change');
                        });
                    }

                    //$('#info-modal').find('.modal-inner').html(responseHtml);	
                    //$('#info-modal').modal('show');				
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }

    }, '.book-btn');



    $(document).on({
        click: function() {

            $.ajax({
                url: "/tpl/cart/booking_step.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&step=' + $(this).data('step') + '&stepback=1',
                dataType: 'html',
                success: function(responseHtml) {
                    $('.booking-wrap').html(responseHtml);

                    if ($('.step_wrap').data('step') == '1') {
                        tripSrhDt();
                    }

                    //$('#info-modal').find('.modal-inner').html(responseHtml);	
                    //$('#info-modal').modal('show');				
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }

    }, '.step-btn');


    $(document).on({
        click: function() {
            var tripInfoData = $('.step_wrap').data('info');
            if (tripInfoData['trip'] == 'A04') {

                var toristAddHtml = '<div class="tourist-card col-6 col-md-12">';
                toristAddHtml += '<div class="trip-row torist-info-row row">';
                toristAddHtml += '<div class="tourist-name col form-group d-none"><input type="text" name="touristNm[]" class="form-control form-control-sm" placeholder="姓名"></div>';
                toristAddHtml += '<div class="tourist-id col-auto form-group d-none"><span><input type="text" name="touristId[]" class="form-control form-control-sm" placeholder="身分證號"></span></div>';
                toristAddHtml += '<div class="tourist-birth col-auto form-group"><span><input type="text" name="touristBirth[]" class="birth-picker form-control form-control-sm"  placeholder="生日"  autocomplete="off" readOnly required><div class="help-block with-errors"></div></span></div>';
                toristAddHtml += '<div class="tourist-age col-3 form-group"><span></span></div>';
                toristAddHtml += '<div class="tourist-prc col-4 form-group"><span></span></div>';
                toristAddHtml += '<div class="tourist-del col-auto form-group"><button type="button" class="tourist-delete btn btn-sm"><span class="fa fa-close"></span></button></div>';
                toristAddHtml += '<div class="diver col-12 d-none"></div>';
                toristAddHtml += '<div class="tourist-meal col-5 form-group  d-none"><span class="mr-3"><input type="checkbox" class=" form-control form-control-sm" autocomplete="off" value="1" onClick="$(this).prop(\'checked\')?$(this).next().val(\'1\'):$(this).next().val(\'0\');"><input type="hidden" name="touristVeg[]" value="0"> 素食</span><span><input type="checkbox" class=" form-control form-control-sm" autocomplete="off" value="1" onClick="$(this).prop(\'checked\')?$(this).next().val(\'1\'):$(this).next().val(\'0\');"><input type="hidden" name="touristNosf[]" value="0"> 不吃海鮮，改肉類</span></div>';

                toristAddHtml += '<div class="diver col-12 mt-1 order-lt-8"></div>';
                toristAddHtml += '<div class="tourist-memo col form-group order-lt-9"><input type="text" name="touristMemo[]" class="form-control form-control-sm" placeholder="附註說明"></div>';

                toristAddHtml += '</div></div>';

            } else {

                var toristAddHtml = '<div class="tourist-card col-6 col-md-12">';
                toristAddHtml += '<div class="trip-row torist-info-row row">';
                toristAddHtml += '<div class="tourist-name col form-group"><input type="text" name="touristNm[]" class="form-control form-control-sm" required placeholder="姓名"><div class="help-block with-errors"></div></div>';
                toristAddHtml += '<div class="tourist-id col-auto form-group"><span><input type="text" name="touristId[]" class="form-control form-control-sm" required  placeholder="身分證號"><div class="help-block with-errors"></div></span></div>';
                toristAddHtml += '<div class="tourist-birth col-auto form-group"><span><input type="text" name="touristBirth[]" class="birth-picker form-control form-control-sm"  placeholder="生日"  autocomplete="off" readOnly required><div class="help-block with-errors"></div></span></div>';
                toristAddHtml += '<div class="tourist-del col-auto form-group"><button type="button" class="tourist-delete btn btn-sm"><span class="fa fa-close"></span></button></div>';
                toristAddHtml += '<div class="diver col-12"></div>';
                toristAddHtml += '<div class="tourist-meal col-5 form-group"><span class="mr-3"><input type="checkbox" class=" form-control form-control-sm" autocomplete="off" value="1" onClick="$(this).prop(\'checked\')?$(this).next().val(\'1\'):$(this).next().val(\'0\');"><input type="hidden" name="touristVeg[]" value="0"> 素食</span><span><input type="checkbox" class=" form-control form-control-sm" autocomplete="off" value="1" onClick="$(this).prop(\'checked\')?$(this).next().val(\'1\'):$(this).next().val(\'0\');"><input type="hidden" name="touristNosf[]" value="0"> 不吃海鮮，改肉類</span></div>';
                toristAddHtml += '<div class="tourist-age col-3 form-group"><span></span></div>';
                toristAddHtml += '<div class="tourist-prc col-4 form-group"><span></span></div>';
                toristAddHtml += '<div class="diver col-12 mt-1 order-lt-8"></div>';
                toristAddHtml += '<div class="tourist-memo col form-group order-lt-9"><input type="text" name="touristMemo[]" class="form-control form-control-sm" placeholder="附註說明"></div>';

                toristAddHtml += '</div></div>';
            }

            $('.tourist-detail').prepend(toristAddHtml);


            var minYr = -1;
            $.each($(this).parents('.step_wrap').eq(0).data('calc'), function(idx, val) {
                if (val['AgeMin'] == null) {
                    minYr = 0;
                } else {
                    if ((minYr == -1) || (parseInt(minYr) >= parseInt(val['AgeMin']))) {
                        console.log(val['AgeMin']);
                        minYr = val['AgeMin'];
                    }
                }
            });
            console.log('最小' + minYr);


            $('.birth-picker').datepicker({
                dateFormat: "yy/mm/dd",
                yearRange: "-100:+0",
                maxDate: -1 * minYr * 365,
                //maxDate: "+0D",
                changeYear: true,
                changeMonth: true
            }).on("change", function() {
                var stepWrap = $(this).parents('.step_wrap').eq(0);
                var tourlistAge = calculateAge($(this).val(), $(stepWrap).data('info')['date']);
                var dtRow = $(this).parents('.torist-info-row').eq(0);
                $(dtRow).find('.tourist-age').data('val', tourlistAge).children('span').text(tourlistAge);

                var tourlistPrc = 0;
                //console.log($(stepWrap).data('calc'));
                $.each($(stepWrap).data('calc'), function(idx, val) {
                    console.log(idx + ' => ' + val['AgeMin'] + ' => ' + val['AgeMax'] + ' => ' + val['Price'] + ' => ' + val['memo']);
                    if (!val['AgeMin']) {
                        if (tourlistAge <= val['AgeMax']) {
                            tourlistPrc = val['Price'];
                        }
                    } else if (!val['AgeMax']) {
                        if (tourlistAge >= val['AgeMin']) {
                            tourlistPrc = val['Price'];
                        }
                    } else {
                        if ((tourlistAge >= val['AgeMin']) && (tourlistAge <= val['AgeMax'])) {
                            tourlistPrc = val['Price'];
                        }
                    }
                });

                $(dtRow).find('.tourist-prc').data('val', tourlistPrc).children('span').text(tourlistPrc);
                //$(dtRow).find('.tourist-prc').data('val',tourlistPrc);
                calcTripSum();
            });


        }

    }, '.tourist-add');

    $(document).on({
        click: function() {
            $(this).parents('.tourist-card').eq(0).remove();
            calcTripSum();
        }

    }, '.tourist-delete');


    $(document).on({
        focus: function() {
            $(this).prop('readonly', true);
        }

    }, '.birth-picker');


    $(document).on({
        click: function() {
            var confirmBookBtn = $(this);
            if (!$('.torist-info-row').length) {
                alert('您需要輸入至少一筆遊客資訊!');
            } else {
                $('#booking-form').find('.birth-picker').prop('readonly', false);
                $('#booking-form').validator('update');
                $('#booking-form').trigger('submit');
                //$('#booking-form').find('.birth-picker').attr('readonly','true');


                if (!$('#booking-form').find('.form-group.has-error').length) {

                    $.ajax({
                        url: "/tpl/cart/booking_modal.php",
                        type: 'post',
                        data: $('#booking-form').serialize() + '&act=confirm_book&bookInfo=' + JSON.stringify($(confirmBookBtn).parents('.step_wrap').eq(0).data('info')) + '&calcInfo=' + JSON.stringify($(confirmBookBtn).parents('.step_wrap').eq(0).data('calc')),
                        dataType: 'html',
                        success: function(responseHtml) {
                            console.log($('#booking-form').serialize() + '&act=confirm_book&bookInfo=' + JSON.stringify($(confirmBookBtn).parents('.step_wrap').eq(0).data('info')) + '&calcInfo=' + JSON.stringify($(confirmBookBtn).parents('.step_wrap').eq(0).data('calc')));
                            $('#info-modal').find('.modal-inner').html(responseHtml);
                            $('#info-modal').modal('show');

                            //$('.step1.step-btn').trigger('click');
                        },
                        error: function(request) {
                            console.log(request.responseText);
                        }
                    });

                }
            }
        }

    }, '.confirm-book-btn');


    $(document).on({
        submit: function(e) {
            e.preventDefault();
        }

    }, '#booking-form');


    tripSrhDt();
});

function calculateAge(birthday, calcday) { // birthday is a date

    var birth = new Date(birthday);
    var now = new Date(calcday);

    var birthMthDay = birthday.split('/')[1] + birthday.split('/')[2];
    var calcMthDay = calcday.split('/')[1] + calcday.split('/')[2];
    var beforeBirth = (birthMthDay < calcMthDay) ? 0 : 1;

    console.log(birthMthDay + ' < ' + calcMthDay + ' => ' + beforeBirth);

    //let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
    return now.getFullYear() - birth.getFullYear() - beforeBirth;
}

function calcTripSum() {
    var tourlistNum = 0;
    var tourlistSum = 0;
    $('.tourist-detail').children('.torist-info-row').each(function(idx, elem) {
        tourlistNum++;
        if ($(elem).find('.tourist-prc').data('val')) {
            tourlistSum += parseInt($(elem).find('.tourist-prc').data('val'));
        }

    });

    $('.tourlist-num').data('val', tourlistNum).text(tourlistNum);
    $('.tourlist-sum').data('val', tourlistSum).text(tourlistSum);

}


function tripSrhDt() {

    //new Date('2018-3-26')

    var d = new Date($("#from").val()),
        j = d.getDate(),
        n = d.getMonth(),
        y = d.getFullYear();
    console.log(n);

    if ((n == 2) && (j == 31) && ($("#from").data('curr') >= 12)) {
        var minDateVal = new Date(y + '/4/2');
        var maxDateVal = new Date(y + '/10/31');
    } else if (n < 3) {
        var minDateVal = new Date(y + '/4/1');
        var maxDateVal = new Date(y + '/10/31');
    } else {
        if ($("#from").data('curr') >= 12) {
            var minDateVal = "+2D";
        } else {
            var minDateVal = "+1D";
        }
        var maxDateVal = new Date(y + '/10/31');
    }

    if (n > 10) {
        var minDateVal = new Date((y + 1) + '/4/1');
        var maxDateVal = new Date((y + 1) + '/10/31');
    }

    var dateFormat = "yy/mm/dd",
        from = $("#from")
        .datepicker({
            dateFormat: dateFormat,
            defaultDate: minDateVal,
            minDate: minDateVal,
            //maxDate: "+3M +7D",
            maxDate: maxDateVal,
            changeMonth: true,
            numberOfMonths: 1
        })
        .on("change", function() {
            var mdate = new Date($(from).datepicker("getDate"));
            mdate.setDate(mdate.getDate() + 7);
            console.log(mdate)

            var newDate = mdate.getFullYear() + '/' + (mdate.getMonth() + 1) + '/' + mdate.getDate();

            to.datepicker("setDate", newDate);

            //to.datepicker("option", "maxDate", mdate);
        }),

        to = $("#to").datepicker({
            dateFormat: dateFormat,
            defaultDate: "+2w",
            changeMonth: true,
            numberOfMonths: 1
        })
        .on("change", function() {
            from.datepicker("option", "maxDate", getDate(this));


            $(this).trigger('change');
        });
}