$( document ).ready(function() {	
	$(document).on({
    	click: function() {
    	    //console.log($('#booking-form').serialize() + '&step=1&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort') + '&opr=' + $(this).data('opr') + '&mthNow='+$('.cdr-mth-sel').data('mth')+'&tripDate='+$('.trip-booking').data('book')['date']);
    	    $.ajax({
                url: "/tpl/cart/new/booking_calendar.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&step=' + $('.step_wrap').data('step') + '&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort') + '&opr=' + $(this).data('opr') + '&mthNow='+$('.cdr-mth-sel').data('mth')+'&tripDate='+$('.trip-booking').data('book')['date'],
                dataType: 'html',
                success: function(responseHtml) {
                    $('.cdr-wrap').html(responseHtml);
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
    	    
    		
        }
    },'#booking-form .mth-change');
    
    
    $(document).on({
    	click: function() {
    	    $('#booking-form .cdr-cell.active').removeClass('active');
    	    $(this).addClass('active');
    		$.ajax({
                url: "/tpl/cart/new/booking_qty.php",
                type: 'post',
                data: $('#booking-form').serialize() + '&step=' + $('.step_wrap').data('step') + '&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort') + '&opr=' + $(this).data('opr') + '&tripDate='+$(this).data('date'),
                dataType: 'html',
                success: function(responseHtml) {
                    $('.qty-wrap').html(responseHtml);
                },
                error: function(request) {
                    console.log(request.responseText);
                }
            });
        }
    },"#booking-form .cdr-cell:not(.disabled)");
    
    $(document).on({
    	click: function() {
            if ($(this).is('.login-required')){
    	    
    	        $.ajax({
                    url: "/tpl/inc/modal_login.php",
                    type: 'post',
                    data: "redir=" + $(this).data('redir'),
                    dataType: 'html',
                    success: function(response) {
                        $('#info-modal').find('.modal-inner').html(response);
                        $('#info-modal').modal('show');
                    },
                    error: function(request) {
    
                    }
                });
                
            }else if ($('.quo-group').data('quo') >= '1'){
    	    
        		$.ajax({
                    url: "/tpl/cart/new/booking_step.php",
                    type: 'post',
           
                    data: $('#booking-form').serialize() + '&step=2&bookInfo=' + JSON.stringify($(this).data('book'))+'&tripSel=' + $('#trip-sel').find('.cat-item.active').data('sort') + '&tripDate='+$('.cdr-cell.active').data('date')+ '&tripQty='+$('.quo-group').data('quo'),
  
                    dataType: 'html',
                    success: function(responseHtml) {
                        $('.booking-wrap').html(responseHtml);
                        
                        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'));
                            var in_age_range = 0;
                            $.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'];
                                        in_age_range++;
                                        console.log('no Min');
                                    }
                                } else if (!val['AgeMax']) {
                                    if (tourlistAge >= val['AgeMin']) {
                                        tourlistPrc = val['Price'];
                                        in_age_range++;
                                        console.log('no Max');
                                    }
                                } else {
                                    if ((tourlistAge >= val['AgeMin']) && (tourlistAge <= val['AgeMax'])) {
                                        tourlistPrc = val['Price'];
                                        in_age_range++;
                                        console.log(val['AgeMin'] + ' ~ '+val['AgeMax']);
                                    }
                                }
                            });
                            console.log('in_age_range:'+in_age_range);
                            if (in_age_range == 0){
                                alert('此年齡無法參加此行程!');
                                $(dtRow).find('.tourist-prc').data('val', '').children('span').text('');
                                $(dtRow).find('.birth-picker').val('');
                            }else{
                                $(dtRow).find('.tourist-prc').data('val', tourlistPrc).children('span').text(tourlistPrc);
                            }
                            //$(dtRow).find('.tourist-prc').data('val',tourlistPrc);
                            calcTripSum();
                        });
                    },
                    error: function(request) {
                        console.log(request.responseText);
                    }
                });
                
    	    }else{
    	        alert('請選擇人數!');
    	    }
        }
    },'#booking-form .trip-booking');
    
    
    $(document).on({
        click: function() {

            $.ajax({
                url: "/tpl/cart/new/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-back-btn');
    

    
    $(document).on({
        click: function() {
            
            var buyCountGroup = $(this).parents('.quo-group').eq(0);
            var buyCount = $(this).parents('.quo-wrap').eq(0).children('.buyCount');

            if ($(buyCountGroup).data('max')) {
                var buyLimit = parseInt($(buyCountGroup).data('max'));
            } else {
                var buyLimit = 99;
            }


            if ($(this).is('.minus')) {
                if (!$(buyCount).val()) {
                    $(buyCount).val(0);
                } else {
                    if ($(buyCount).val() > 0) {
                        $(buyCount).val(parseInt($(buyCount).val()) - 1);
                    }
                }
            }

            if ($(this).is('.plus')) {
                if (!$(buyCount).val()) {
                    $(buyCount).val(1);
                } else {

                    if (parseInt($(buyCount).val()) < buyLimit) {
                        $(buyCount).val(parseInt($(buyCount).val()) + 1);
                    }
                }
            }
            
            var quo_total = 0;
            var amt_total = 0;
            
            $(buyCountGroup).find('.buyCount').each(function(){
                quo_total += parseInt($(this).val());
                amt_total += parseInt($(this).data('prc')) * parseInt($(this).val());
            });
            
            $(buyCountGroup).data('quo',quo_total);
            
            if (amt_total > 0){
                $('.total-wrap').html('<span class="text-muted">總金額 <span class="text-info">TWD '+amt_total+'</span></span>');
            }else{
                $('.total-wrap').html('');
            }

            $(this).parents('.quo-wrap').eq(0).children('.plus').prop('disabled', false);
            $(this).parents('.quo-wrap').eq(0).children('.minus').prop('disabled', false);

            if (parseInt($(buyCount).val()) <= 0) {
                $(this).parents('.quo-wrap').eq(0).children('.minus').prop('disabled', true);
            }
            if (parseInt(quo_total) >= buyLimit) {
                $(this).parents('.quo-wrap').eq(0).children('.plus').prop('disabled', true);
                $(buyCountGroup).find('.plus').prop('disabled', true);
            }else{
                $(this).parents('.quo-wrap').eq(0).children('.plus').prop('disabled', false);
                $(buyCountGroup).find('.plus').prop('disabled', false);
            }
        }

    }, ".quo-wrap .minus, .quo-wrap .plus");
    
    $(document).on({
        focus: function(){
            $(this).data('preval',$(this).val()); 
            $(this).select();
        },
        keyup: function() {
            this.value = this.value.replace(/[^0-9\.]/g, '1');
        
        
        
            var buyCountGroup = $(this).parents('.quo-group').eq(0);
    
            if ($(buyCountGroup).data('max')) {
                var buyLimit = parseInt($(buyCountGroup).data('max'));
            } else {
                var buyLimit = 99;
            }
    
            var quo_total = 0;
            var amt_total = 0;
                
            $(buyCountGroup).find('.buyCount').each(function(){
                quo_total += parseInt($(this).val());
                amt_total += parseInt($(this).data('prc')) * parseInt($(this).val());
            });
            
            if (quo_total > buyLimit){
                $(this).val($(this).data('preval'));
                
                quo_total = 0;
                amt_total = 0;
                
                $(buyCountGroup).find('.buyCount').each(function(){
                    quo_total += parseInt($(this).val());
                    amt_total += parseInt($(this).data('prc')) * parseInt($(this).val());
                });
                
            }
                
            $(buyCountGroup).data('quo',quo_total);
            
            if (amt_total > 0){
                $('.total-wrap').html('<span class="text-muted">總金額 <span class="text-info">TWD '+amt_total+'</span></span>');
            }else{
                $('.total-wrap').html('');
            }
                
            if (parseInt($(this).val()) <= 0) {
                $(this).parents('.quo-wrap').eq(0).children('.minus').prop('disabled', true);
            }else if (quo_total >= buyLimit) {
                $(buyCountGroup).find('.plus').prop('disabled', true);
            } else {
                $(this).parents('.quo-wrap').eq(0).children('.plus').prop('disabled', false);
                $(this).parents('.quo-wrap').eq(0).children('.minus').prop('disabled', false);
            }
        }
    },'.quo-wrap .buyCount');
    

    
    
    $(document).on({
        click: function(e) {
            if (!$('#pagearea').length) {
                e.preventDefault();
                e.stopPropagation();
                $.ajax({
                    url: "/tpl/inc/modal_login.php",
                    type: 'post',
                    data: "redir="+$(this).attr('href'),
                    dataType: 'html',
                    success: function(response) {
                        $('#info-modal').find('.modal-inner').html(response);
                        $('#info-modal').modal('show');
                    },
                    error: function(request) {
    
                    }
                });
    
            }
            
        }
    }, '.trip-link-btn.login-required');
    
    



});

