var cdp_shortcode_data = {};
var cdp_shortcode_call = '';
var cdp_shortcode_request = '';

//inventory_search
if (jQuery('.cdp-inventory-shortcode.search-shortcode-container').length) {
    jQuery('.shortcode-input-action').change(function (e) {
        searchParent = jQuery(e.target).parents('.cdp-inventory-shortcode.search-shortcode-container');
        cdp_shortcode_request = jQuery(e.target).attr('name');
        if (cdp_shortcode_request == 'saleclass' && jQuery(e.target).val() == '') {
            jQuery(searchParent).find('select.lockable').prop('disabled', true);
        } else {
            jQuery(searchParent).addClass('running').find('select.lockable').prop('disabled', true);
            cdp_shortcode_call = 'search_shortcode';
            jQuery(searchParent).find('select').each(function () {
                cdp_shortcode_data[jQuery(this).attr('name')] = jQuery(this).val();
            });
            cdp_shortcode_data['search'] = jQuery(searchParent).find('.shortcode-input-search').val();
            cdp_shortcode_ajax_call().done(function (result) {
                cdp_shortcode_update_dropdown(searchParent, result['content']['dropdown']);
            }).fail(function () {
                //console.log('Connection Error');
            });
            jQuery(searchParent).removeClass('running');
            cdp_shortcode_request = cdp_shortcode_call = '';
            cdp_shortcode_data = {};
        }
    });

    jQuery('.shortcode-search-button').click(function (e) {
        searchParent = jQuery(e.target).parents('.cdp-inventory-shortcode.search-shortcode-container');
        cdp_shortcode_request = jQuery(e.target).attr('data-name');
        cdp_shortcode_call = 'search_shortcode';
        jQuery(searchParent).find('select').each(function () {
            cdp_shortcode_data[jQuery(this).attr('name')] = jQuery(this).val();
        });
        cdp_shortcode_data['search'] = jQuery(searchParent).find('.shortcode-input-search').val();
        cdp_shortcode_ajax_call().done(function (result) {
            window.location = result['url'];
        }).fail(function () {
            //console.log('Connection Error');
        });
    });
}

function cdp_shortcode_update_dropdown(parentWrapper, data) {
    hideCounts = jQuery(parentWrapper).find('.hide-counts').length;
    jQuery(searchParent).find('select.lockable').each(function () {
        jQuery(this).children().remove();
        jQuery(this).append('<option value="0">' + jQuery(this).attr('name').shortcode_capitalizeFirstLetter() + 's</option>');
    });
    jQuery.each(data, function (key, values) {
        jQuery(parentWrapper).find('.shortcode-select-' + key).children().remove();
        //var list = '<option value="0">All '+key.extender_capitalizeFirstLetter()+'s</option>';
        var list = '<option value="0">All</option>';
        jQuery.each(values['data'], function (id, item) {

            if (values['needle'] == item) {
                selected = 'selected';
            } else {
                selected = '';
            }
            if (values['dataCount'] && values['dataCount'][item] && !hideCounts) {
                count = '(' + values['dataCount'][item] + ')';
            } else {
                count = '';
            }
            list += '<option value="' + item + '" ' + selected + '>' + item + ' ' + count + '</option>';

        })
        jQuery(parentWrapper).find('.shortcode-select-' + key).append(list);
        jQuery(parentWrapper).find('.shortcode-select-' + key).prop('disabled', false);
    })
}

//inventory_search
function cdp_shortcode_ajax_call() {
    return jQuery.ajax({
        url: ajax_object.url,
        data: {
            'action': 'sc_ajax_handler',
            'handler': cdp_shortcode_call,
            'params': cdp_shortcode_data,
            'request': cdp_shortcode_request,
            'nonce' : ajax_object.nonce
        },
        dataType: 'json',
        beforeSend: function () {
        },
        complete: function () {

        },
        success: function (data) {

        },
        error: function (xhr, status, error) {

        }
    });
}

if (jQuery('#sc-detail-container').length) {
    var iframe_src;
    jQuery('#sc-detail-container').on('click', '.dialog-me', function (e) {
        iframe_src = '/' + jQuery(this).attr('data-key') + '/?form_id=' + jQuery(this).attr('data-form') + '&vin=' + jQuery(this).attr('data-vin');
        jQuery('#iframe-container').dialog('open')
    })
    jQuery("#iframe-container").dialog({
        autoOpen: false,
        modal: true,
        closeText: 'Cancel',
        dialogClass: 'sc-detail-form',
        width: 400,
        maxWidth: 400,
        maxHeight: 500,
        height: 500,
        open: function (ev, ui) {
            jQuery('#iframe-dialog').attr('src', iframe_src);
            jQuery('#sc-detail-container').addClass('modal');
        },
        close: function (ev, ui) {
            jQuery('#iframe-dialog').attr('src', '');
            jQuery('#sc-detail-container').removeClass('modal');
        }
    });
}

jQuery(document).ready(function () {

    if (jQuery('.sc-slider-container').length) {
        jQuery('.sc-slider-container').each(function () {
            container_width = jQuery(this).width();
            item_width = jQuery(this).find('.sc-slider-item').width();
            if (item_width > 0) {
                ds_count = Math.floor(container_width / item_width);
                b1_count = Math.floor(720 / item_width);
                b2_count = Math.floor(600 / item_width);
                b3_count = Math.floor(480 / item_width);
                b4_count = Math.floor(420 / item_width);
                b5_count = Math.floor(400 / item_width);
                b6_count = Math.floor(360 / item_width);
            } else {
                ds_count = b1_count = b2_count = b3_count = b4_count = b5_count = b6_count = 0;
            }

        });

        var sc_inventory_slider   = new Splide(
            '.sc-slider-container',
            {
                width: '100%',
                fixedWidth: 200,
                gap: 10,
                autoplay: true,
                perPage: ds_count,
                perMove: ds_count,
                cover: true,
                breakpoints: {
                    720: {
                        perPage: b1_count,
                        perMove: b1_count,
                    },
                    600: {
                        perPage: b2_count,
                        perMove: b2_count,
                    },
                    480: {
                        perPage: b3_count,
                        perMove: b3_count,
                    },
                    420: {
                        perPage: b4_count,
                        perMove: b4_count,
                    },
                    400: {
                        perPage: b5_count,
                        perMove: b5_count,
                    },
                    360: {
                        perPage: b6_count,
                        perMove: b6_count,
                    },
                    320: {
                        perPage: 1,
                        perMove: 1,
                    }
                }
            }
        );
        sc_inventory_slider.mount();
    }
})


//Button Click - regular
jQuery('#sc-detail-container').on('click', '.sc-action-button', function (e) {
    key = jQuery(e.target).attr('data-key');
    display = jQuery(e.target).attr('data-name');
    if (jQuery(e.target).hasClass('inner-button')) {
        jQuery('#' + key + ' .bottom-button.active').removeClass('active');
        jQuery('#' + key + ' .bottom-content.active').removeClass('active');
        jQuery('#' + key + ' .' + display + '-button').addClass('active');
        jQuery('#' + key + ' .' + display + '-content').addClass('active');
    } else if (jQuery(e.target).hasClass('inner-tab-button')) {
        jQuery('#' + key + ' .tab-button.active').removeClass('active');
        jQuery('#' + key + ' .tab-content.active').removeClass('active');
        jQuery('#' + key + ' .' + display + '-button').addClass('active');
        jQuery('#' + key + ' .' + display + '-content').addClass('active');
    } else {
        if (jQuery('#' + key).hasClass('active')) {
            jQuery('#' + key).removeClass('active');
            jQuery('#' + key + ' .sc-detail-bottom-container').removeClass('active');
            jQuery(e.target).text('Show Details');
        } else {
            jQuery('#' + key).addClass('active').addClass('viewed');
            jQuery('#' + key + ' .sc-detail-bottom-container').addClass('active');
            jQuery('#' + key + ' .' + display + '-button').addClass('active');
            jQuery('#' + key + ' .' + display + '-content').addClass('active');
            jQuery(e.target).text('Hide Details');
            jQuery('html,body').animate({scrollTop: jQuery('#' + key).offset().top - 100}, 1000);
            //alert( jQuery('#'+key).offset().top );
        }
    }
});

//Button Click - ajax
jQuery('#sc-detail-container').on('click', '.sc-action-ajax', function (e) {
    key = jQuery(e.target).attr('data-key');
    display = jQuery(e.target).attr('data-name');
    tag = jQuery(e.target).attr('data-tag');
    container = '#' + key + ' .' + display + '-content';

    data = {'key': key, 'tag': tag};

    jQuery('#' + key + ' .bottom-button.active').removeClass('active');
    jQuery('#' + key + ' .bottom-content.active').removeClass('active');
    jQuery('#' + key + ' .' + display + '-button').addClass('active');
    jQuery('#' + key + ' .' + display + '-content').addClass('active');

    if (jQuery('#' + key + ' .' + display + '-content').hasClass('loaded')) {
        //Do Nothing already loaded
    } else {
        cdp_front_ajax_call('get_vehicle_details', data, container).done(function (result) {
            jQuery('#' + key + ' .' + display + '-content').addClass('loaded');
            cdp_call_lightbox();
        }).fail(function () {
            alert('Connection Error: Could not retrieve data.');
        });
    }
});

//Form Call
jQuery('#sc-detail-container').on('click', '.sc-action-form', function (e) {
    key = jQuery(e.target).attr('data-key');
    display = jQuery(e.target).attr('data-name');
    container = '#' + key + ' .' + display + '-content';
    form_id = jQuery(this).attr('data-form-id');

    var form_data = {};
    jQuery('#' + key + ' .form-value').each(function () {
        form_data[jQuery(this).attr('data-name')] = jQuery(this).text();
    });

    data = {'key': key, 'form': form_id, 'hooks': form_data};

    if (jQuery(e.target).hasClass('sc-detail-button')) {
        jQuery('#' + key).addClass('active')
        jQuery('#' + key + ' .sc-detail-bottom-container').addClass('active');
        jQuery(e.target).siblings('.show-details').text('Hide Details');
    }

    jQuery('#' + key + ' .bottom-button.active').removeClass('active');
    jQuery('#' + key + ' .bottom-content.active').removeClass('active');
    jQuery('#' + key + ' .' + display + '-button').addClass('active');
    jQuery('#' + key + ' .' + display + '-content').addClass('active');
    jQuery('#' + key + ' .' + display + '-content .list-form-wrapper').remove();

    cdp_front_ajax_call('get_gform', data, container).done(function (result) {

    }).fail(function () {
        alert('Connection Error: Could not retrieve data.');
    });

});

//Mobile Action
jQuery('#mobile-action-button').click(function () {
    if (jQuery('#sc-detail-mobile-wrapper').hasClass('active')) {
        jQuery('#sc-detail-mobile-wrapper').removeClass('active');
        jQuery('#sc-detail-search-container .sc-search-item').removeClass('mobile');
    } else {
        jQuery('#sc-detail-mobile-wrapper').addClass('active');
        jQuery('#sc-detail-search-container .sc-search-item').addClass('mobile');
    }
})

function cdp_ajax_loader_display() {
    div_el = document.createElement('div');
    jQuery(div_el).addClass('ajax-loader').text('Getting requested data.');
    img_el = document.createElement('img');
    jQuery(img_el).attr('src', ajax_object.img_src + 'templates/inventory/spinner.gif');

    element = jQuery(div_el).append(img_el);
    return element;
}

// AJAX Call
function cdp_front_ajax_call(fn, params, wrapper) {
    // console.log('DEBUG: cdp_front_ajax_call fn ', fn);
    // console.log('DEBUG: cdp_front_ajax_call params ', params);
    return jQuery.ajax({
        url: ajax_object.url,
        data: {'action': 'sc_ajax_handler', 'handler': fn, 'params': params, 'nonce': ajax_object.nonce },
        dataType: 'json',
        beforeSend: function () {
            jQuery(wrapper).append(cdp_ajax_loader_display());
        },
        complete: function () {

        },
        success: function (data) {
            if (!ajax_dropdown) {
                jQuery(wrapper).append(data['content']);
            } else {
                cdp_update_dropdowns(data);
            }
            jQuery('.ajax-loader').remove();

        },
        error: function (xhr, status, error) {
            alert('Ajax call failed.');
            alert(error);
        }
    });
}

function cdp_call_lightbox() {
    lightbox.option({
        imageClickClose: false,
        loopImages: true,
        fitToScreen: true,
        scaleImages: true,
        xScale: 1.0,
        yScale: 1.0,
        displayDownloadLink: true
    });
}

function cdp_get_ajax_loader_data() {
    var data = {};
    jQuery('#cdp-ajax-loader').children().each(function () {
        data[jQuery(this).attr('data-key')] = jQuery(this).text();
    });
    return data;
}

function cdp_get_vehicles() {
    container = document.getElementById('sc-detail-container');
    var ajax_data = cdp_get_ajax_loader_data();

    ajax_data['page'] = ajax_page;

    data = {'atts': ajax_data};
    cdp_front_ajax_call('get_more_vehicles', data, container).done(function (result) {
        ajax_loading = false;
        ajax_page++;
    }).fail(function () {
        alert('Connection Error: Could not retrieve data.');
    });
}

function cdp_update_ajax_params(value, key) {
    var add_param = true;
    jQuery('#cdp-ajax-loader').children().each(function () {
        if (jQuery(this).attr('data-key') == key) {
            add_param = false;
            jQuery(this).text(value);
        }
    })
    if (add_param) {
        jQuery('#cdp-ajax-loader').append('<div data-key="' + key + '">' + value + '</div>');
    }
}

function cdp_update_dropdowns(data) {
    jQuery.each(data, function (key, items) {
        cdp_update_ajax_params(items['att'], key);
        jQuery('#sc-search-' + key).children().remove();
        jQuery('#sc-search-' + key).append(items['display']);
        if (jQuery.isEmptyObject(items['disabled'])) {
            jQuery('#sc-search-' + key).prop('disabled', false);
        } else {
            jQuery('#sc-search-' + key).prop('disabled', true);
        }
    });
}

function cdp_get_dropdown_data(filter) {
    container = document.getElementById('sc-detail-container');
    ajax_dropdown = true;
    data = {'atts': cdp_get_ajax_loader_data(), 'filter': filter};
    cdp_front_ajax_call('update_dropdowns', data, container).done(function (result) {
        ajax_dropdown = false;
        cdp_get_vehicles();
    }).fail(function () {
        alert('Connection Error: Could not retrieve data.');
    });
}

function cdp_vehicle_caller(val, filter) {

    cdp_update_ajax_params(val, filter);

    ajax_loading = true;
    ajax_page = 1;
    jQuery('#sc-detail-container .sc-detail-item').remove();
    jQuery('#cdp-ajax-end').remove();
    if (filter != 'trim') {
        cdp_get_dropdown_data(filter);
    } else {
        cdp_get_vehicles();
    }
}

function cdp_yHandler() {
    if (jQuery('#sc-detail-container').length) {
        var container = document.getElementById('sc-detail-container');
        var contentTop = jQuery(container).offset().top + 25;
        var contentHeight = container.offsetHeight + 350;
        var yOffset = window.pageYOffset;
        var windowY = yOffset + window.innerHeight;

        if (jQuery('#sc-detail-search-container').length) {
            if (contentTop <= yOffset) {
                jQuery('#sc-detail-search-container').addClass('scroll');
            } else {
                jQuery('#sc-detail-search-container').removeClass('scroll');
            }
        }
        if (windowY >= contentHeight && !ajax_loading && !jQuery('#cdp-ajax-end').length) {
            // Ajax call to get more dynamic data goes here
            ajax_loading = true;
            cdp_get_vehicles(container);
        }

        var status = document.getElementById('cdp-ajax-status');
        status.innerHTML = contentTop + " | " + yOffset + " | " + windowY;
    }
}

var ajax_loading = false;
var ajax_page = 2;
var ajax_dropdown = false;
window.onscroll = cdp_yHandler;


String.prototype.shortcode_capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
