jQuery.noConflict()(function($) {

    jQuery('.book_now_btn').on('click', function () {
        $(this).html($(this).data('wait'));

        formData = getFormData(jQuery(this).parent('form'));
        var data = {
            action: 'tmbooking_redirect_to_cart',
            data: formData
        };

        jQuery.post( tm_booking_ajax.url, data, function(response) {

             console.log(response);

            if(response.redirect != undefined){
                document.location.href = response.redirect;
                $(this).html($(this).data('booknow'));
            }

            if(response.error != undefined){
                $(".tm_price_total").html(response.error);
            }
        });
    });



    jQuery("form.booking_form").change(function(event){
        formData = getFormData(jQuery(this));
        var ID = jQuery(this).children('.hidden_id').val();
        var this_form = jQuery('form.booking_form');

        if(jQuery(this).find('.start_date').val() !== '' && jQuery(this).find('.start_date').val() !== 'end_date'){
            this_form.addClass('loading');
            var data = {
                action: "tmbooking_change_total",
                data: formData
            };
            //console.log(formData);
            $.post( tm_booking_ajax.url, data, function(response) {
                $(".tm_price_total" + ID).html(response);
                this_form.removeClass('loading');
            });
        }

    });


    function getFormData($form){
        var unindexed_array = $form.serializeArray();
        var indexed_array = {};
        var extra_ids_val = "";

        $.map(unindexed_array, function(n, i){
            indexed_array[n['name']] = n['value'];
            if(n["name"] === "extra[]"){
                extra_ids_val += n["value"] + ",";
            }
            indexed_array["extra_ids"] = extra_ids_val.slice(0,-1);
        });

        return indexed_array;
    }

});