/**
 * Handle attribute selection
 */
function handleAttributeSelect()
{
    // Enable options
    var combination_selector = $('#combination-selector');
    combination_selector.find('select').prop('disabled', false);

    $(document).on('change', '#attribute_form select', function() {

        // Reload combination selector
        combination_selector = $('#combination-selector');
        combination_selector.find('select').not('[name="' + $(this).attr('name') + '"]').prop('disabled', true);

        // Form Variables
        var url = combination_selector.data('url');
        var form = combination_selector.find('form');
        var action_attribute_id = $(this).data('attribute-id');
        var option_value = $(this).val();
        var option = $('option[value="' + option_value + '"]')
        var reset = option.hasClass('not-available') ? true : false;

        // List all Attribute Value Ids
        var attribute = {};
        $.each(combination_selector.find('select'), function() {
            if (this.value != '-- Please Select --' && (!option.hasClass('not-available') || option_value == this.value)) {
                var attribute_id = this.name.replace('attribute[', '').replace(']', '');
                attribute[attribute_id] = this.value;
            }
        });

        // Setup the ajax call
        var request = $.ajax({
            url         : url,
            type        : 'POST',
            data        : {
                _token: form.find('[name="_token"]').val(),
                action_attribute_id: action_attribute_id,
                attribute: attribute,
                reset: reset
            }
        });

        // Ajax Success
        request.success(function(data)
        {
            combination_selector.replaceWith(data);
            $('#combination-selector').find('select').prop('disabled', false);
            $.event.trigger("combinationUpdate");
        });

    });
}

/**
 * Reset product combination form
 */
function resetProductCombinationForm() {
    var combination_selector = $('#combination-selector');

    // Setup the ajax call
    var request = $.ajax({
        url         : combination_selector.data('url'),
        type        : 'POST',
        data        : {
            _token: $('[name="_token"]').val(),
            action_attribute_id: null,
            attribute: null,
            reset: true
        }
    });

    // Ajax Success
    request.success(function(data)
    {
        combination_selector.replaceWith(data);
        $('#combination-selector').find('select').prop('disabled', false);
        $.event.trigger("combinationUpdate");
    });
}


/**
 * Handle related products
 */
function handleRelatedProducts()
{
    $('#related-products').carousel({
        interval : 10000
    });
}


/**
 * Document ready function
 */
$(document).ready(function()
{
    handleRelatedProducts();
});

handleAttributeSelect();
