$(document).ready(function () {

    $("body").on("click", '.remove', remove);
    $("body").on("change", '.city', getHotel);
    $("body").on("change", '.hotelnm', getHotelCatg);
    $("body").on("keyup", '.rate', getcalc);
    $("body").on("blur change", '.checkin, .checkout', calHotel);


    function daysdifference(firstDate, secondDate) {
        var startDay = new Date(firstDate);
        var endDay = new Date(secondDate);

// Determine the time difference between two dates     
        var millisBetween = startDay.getTime() - endDay.getTime();

// Determine the number of days between two dates  
        var days = millisBetween / (1000 * 3600 * 24);

// Show the final number of days between dates     
        return Math.round(Math.abs(days));
    }


    function calHotel() {
        var tr = $(this).closest("tr"),
            fcheckin = tr.find(".checkin").val(),
            fcheckout = tr.find(".checkout").val();
        if (fcheckin != "0000-00-00" && fcheckout != "0000-00-00") {
            var days = daysdifference(fcheckin, fcheckout);
//        alert(days);
        }
        tr.find(".nonights").val(days);
    }
    
    
    function getcalc() {
        var tr = $(this).closest("tr"),
        
        days = tr.find(".nonights").val();
        qty = tr.find(".qty").val(),
        rate = tr.find(".rate").val();

        amount = (days * qty * rate).toFixed(2);

        tr.find(".amount").val(amount);

    }


    function getHotel() {
        var city = $(".city").val();
        $.post('getHotel.php', {city: city}, function (data) {
            $(".hotelnm").html(data);
        });
    }


    function getHotelCatg() {
        var hotelnm = $(".hotelnm").val();
        $.post('getHotelCatg.php', {hotelnm: hotelnm}, function (data) {
            $(".hotelcatg").html(data);
        });
    }


    $('#addnew').click(function () {
        AddRows();
    });

    

    function AddRows() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var detail = ".fetchpart_" + ctr;

        $.post('hotelpurch_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('.tbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }

    function remove() {
        $(this).closest("tr").remove();
    }


});