<?php
/**
 * Created by PhpStorm.
 * User: krichardson
 * Date: 10/10/22
 * Time: 2:17 PM
 */


$io_widget_cart = 0;

// The widget class
class Widget_Filter extends WP_Widget {
    // Main constructor
    public function __construct()
    {
        parent::__construct(
            'Widget_Filter',
            __('InflatableOffice Product Filter', 'text_domain'),
            array(
                'customize_selective_refresh' => true,
            )
        );
    }
    // The widget form (for the backend )
    public function form( $instance )
    {
        $filter_data = json_decode(get_option("io_filter_data"));

        $defaults = array(
            //'dimensions' => 1,
            //'circuits' => 1,
            //'space_required' => 1,
            'filter_availability' => 1,
            'filter_price' => 1,
            'filter_price_mode' => '1hr',
            'filter_size' => 0,
            'filter_size_unit' => "feet",
            'filter_size_mode' => "length-width-height",
            'filter_size_max' => "15",
            'filter_size_min' => "10",
            'filter_scroll' => 0,
            'display_type' => 'horizontal',
            'column_width' => '120',
            'number_of_columns' => '2',
            'customGroupsData' => '',
            'search_type' => 'exclusive',
            'search_button_text' => 'Search',
            'reset_button_text' => 'Reset'
        );

        foreach($filter_data as $data_name => $data) {
            $defaults['optField_'.str_replace(" ", "_", $data_name)] = 0;
        }

        extract(wp_parse_args(( array )$instance, $defaults));

        $dimensions_checked = '';
        if(!empty($dimensions)) $dimensions_checked = 'checked="checked"';
        $circuits_checked = '';
        if(!empty($circuits)) $circuits_checked = 'checked="checked"';
        $space_required_checked = '';
        if(!empty($space_required)) $space_required_checked = 'checked="checked"';
        $filter_scroll_checked = '';
        if(!empty($filter_scroll)) $filter_scroll_checked = 'checked="checked"';
        $filter_availability_checked = '';
        if(!empty($filter_availability)) $filter_availability_checked = 'checked="checked"';
        $filter_price_checked = '';
        if(!empty($filter_price)) $filter_price_checked = 'checked="checked"';
        $filter_size_checked = '';
        if(!empty($filter_size)) $filter_size_checked = 'checked="checked"';

        $display_vertical_checked = '';
        $display_horizontal_checked = '';
        if(!empty($display_type)){
            if($display_type == 'vertical'){
                $display_vertical_checked = 'checked="checked"';
                $display_horizontal_checked = '';
            }else if($display_type == 'horizontal'){
                $display_vertical_checked = '';
                $display_horizontal_checked = 'checked="checked"';
            }
        }

        $filter_price_mode_1hr_checked = '';
        $filter_price_mode_userInput_checked = '';
        if(!empty($filter_price_mode)){
            if($filter_price_mode == '1hr'){
                $filter_price_mode_1hr_checked = 'checked="checked"';
                $filter_price_mode_userInput_checked = '';
            }else if($filter_price_mode == 'userInput'){
                $filter_price_mode_1hr_checked = '';
                $filter_price_mode_userInput_checked = 'checked="checked"';
            }
        }

        $io_filter_size_mode_lwh_checked  = '';
        $io_filter_size_mode_lw_checked = '';
        $io_filter_size_mode_area_checked = '';
        if(!empty($filter_size_mode)){
            if($filter_size_mode == 'length-width-height'){
                $io_filter_size_mode_lwh_checked = 'checked="checked"';
                $io_filter_size_mode_lw_checked = '';
                $io_filter_size_mode_area_checked = '';
            }else if($filter_size_mode == 'length-width'){
                $io_filter_size_mode_lwh_checked = '';
                $io_filter_size_mode_lw_checked = 'checked="checked"';
                $io_filter_size_mode_area_checked = '';
            }
            else if($filter_size_mode == 'area'){
                $io_filter_size_mode_lwh_checked = '';
                $io_filter_size_mode_lw_checked = '';
                $io_filter_size_mode_area_checked = 'checked="checked"';
            }
        }

        foreach($filter_data as $data_name => $data) {
            ${'optField_'.str_replace(" ", "_", $data_name).'_checked'} = '';
            if(!empty(${'optField_'.str_replace(" ", "_", $data_name)})) ${'optField_'.str_replace(" ", "_", $data_name).'_checked'} = 'checked="checked"';
        }

        if(!empty($customGroupsData)){
            $customGroupsData_obj = json_decode($customGroupsData);
        }

        ?>
        <!-- <input class="widefat" id="<?php //echo esc_attr($this->get_field_id('dimensions')); ?>"
               name="<?php //echo esc_attr($this->get_field_name('dimensions')); ?>" type="checkbox"
               value="1" <?php //echo esc_attr($dimensions_checked); ?>"/>
        <label
            for="<?php //echo esc_attr($this->get_field_id('dimensions')); ?>"><?php //_e('Dimensions', 'text_domain'); ?></label>
        <br>
        <input class="widefat" id="<?php //echo esc_attr($this->get_field_id('circuits')); ?>"
               name="<?php //echo esc_attr($this->get_field_name('circuits')); ?>" type="checkbox"
               value="1" <?php //echo esc_attr($circuits_checked); ?>"/>
        <label
            for="<?php //echo esc_attr($this->get_field_id('circuits')); ?>"><?php //_e('Circuits', 'text_domain'); ?></label>
        <br>
        <input class="widefat" id="<?php //echo esc_attr($this->get_field_id('space_required')); ?>"
               name="<?php //echo esc_attr($this->get_field_name('space_required')); ?>" type="checkbox"
               value="1" <?php //echo esc_attr($space_required_checked); ?>"/>
        <label
            for="<?php //echo esc_attr($this->get_field_id('space_required')); ?>"><?php //_e('Space Required', 'text_domain'); ?></label>
        <br>
        <br>
        <H3>Optional Fields</H3>
        <hr> -->
        <lable class="io_fld_title" for="<?php echo $this->get_field_id('search_button_text')?>" >Search Button Text:</lable>
        <input type="text" id="customGroupInput" name="<?php echo $this->get_field_name('search_button_text'); ?>" value="<?php echo $search_button_text; ?>">
        <lable class="io_fld_title" for="<?php echo $this->get_field_id('reset_button_text')?>" >Reset Button Text:</lable>
        <input type="text" id="customGroupInput" name="<?php echo $this->get_field_name('reset_button_text'); ?>" value="<?php echo $reset_button_text; ?>">
        <lable class="io_fld_title" for="<?php echo $this->get_field_id('reset_button_text')?>" >Search Type:</lable>
        <select id="<?php echo $this->get_field_id('search_type')?>"
                name = "<?php echo $this->get_field_name('search_type')?>"
                class="widefat" value = "<?php echo esc_attr($search_type); ?>">
            <option value="inclusive" <?php echo ($search_type === 'inclusive') ? 'selected' : ''; ?>>Inclusive</option>
            <option value="exclusive" <?php echo ($search_type === 'exclusive') ? 'selected' : ''; ?>>Exclusive</option>
        </select>
        <br>
        <br>
        <hr>
        <br>
        <?php
        foreach($filter_data as $name => $data) {
            ?>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id("optField_".str_replace(" ", "_", $name))); ?>"
                   name="<?php echo esc_attr($this->get_field_name("optField_".str_replace(" ", "_", $name))); ?>" type="checkbox"
                   value="1" <?php echo esc_attr(${'optField_'.str_replace(" ", "_", $name).'_checked'}); ?>"/>
            <label
                    for="<?php echo esc_attr($this->get_field_id("optField_".str_replace(" ", "_", $name))); ?>"><?php _e($name, 'text_domain'); ?></label>
            <?php
            echo "<br>";
        }
        ?>
        <input class="widefat" id="<?php echo $this->get_field_id('filter_availability')?>"
               name="<?php echo $this->get_field_name('filter_availability')?>"
               type="checkbox" value="1" <?php echo esc_attr($filter_availability_checked); ?>/>
        <label for="<?php echo $this->get_field_id('filter_availability')?>">Allow filter by availability on date selected</label>
        <br>
        <input class="widefat" id="<?php echo $this->get_field_id('filter_price')?>"
               name="<?php echo $this->get_field_name('filter_price')?>"
               type="checkbox" value="1" <?php echo esc_attr($filter_price_checked); ?>/>
        <label for="<?php echo $this->get_field_id('filter_price')?>">Enable filter by pricing.</label>
        <div style="margin-left:10px" id="io_filter_price_select">
            <input type="radio" name="<?php echo $this->get_field_name('filter_price_mode')?>" id="io_filter_price_mode_1hr"
                   value="1hr" <?php echo $filter_price_mode_1hr_checked; ?>  class="widefat" />
            <label for="io_filter_price_mode_1hr" class="io_fld_title"><?php _e( "One hour price", 'io' ); ?></label><br>
            <input type="radio" name="<?php echo $this->get_field_name('filter_price_mode')?>" id="io_filter_price_mode_userInput"
                   value="userInput" <?php echo $filter_price_mode_userInput_checked; ?>  class="widefat" />
            <label for="io_filter_price_mode_userInput" class="io_fld_title"><?php _e( "User input price", 'io' ); ?></label><br>
        </div>
        <br>
        <input class="widefat" id="<?php echo $this->get_field_id('filter_size')?>"
               name="<?php echo $this->get_field_name('filter_size')?>"
               type="checkbox" value="1" <?php echo esc_attr($filter_size_checked); ?>/>
        <label class="io_fld_title" for="<?php echo $this->get_field_id('filter_size')?>">Enable filter by size.</label>
        <div style="margin-left:10px" id="io_filter_size_options">
            <input type="radio" name="<?php echo $this->get_field_name('filter_size_mode')?>" id="io_filter_size_mode_lwh"
                   value="length-width-height" <?php echo $io_filter_size_mode_lwh_checked; ?>  class="widefat" />
            <label for="io_filter_size_mode_lwh" class="io_fld_title"><?php _e( "Length, width, and height", 'io' ); ?></label><br>
            <input type="radio" name="<?php echo $this->get_field_name('filter_size_mode')?>" id="io_filter_price_mode_lw"
                   value="length-width" <?php echo $io_filter_size_mode_lw_checked; ?>  class="widefat" />
            <label for="io_filter_price_mode_lw" class="io_fld_title"><?php _e( "Length and width", 'io' ); ?></label><br>
            <input type="radio" name="<?php echo $this->get_field_name('filter_size_mode')?>" id="io_filter_price_mode_area"
                   value="area" <?php echo $io_filter_size_mode_area_checked; ?>  class="widefat" />
            <label for="io_filter_price_mode_area" class="io_fld_title"><?php _e( "Area", 'io' ); ?></label><br>
            <lable class="io_fld_title" for="<?php echo $this->get_field_id('filter_size_unit')?>" >Units:</lable>
            <select id="<?php echo $this->get_field_id('filter_size_unit')?>"
                    name = "<?php echo $this->get_field_name('filter_size_unit')?>"
                    class="widefat" value = "<?php echo esc_attr($filter_size_unit); ?>">
                <option value="inches" <?php echo ($filter_size_unit === 'inches') ? 'selected' : ''; ?>>Inches</option>
                <option value="feet" <?php echo ($filter_size_unit === 'feet') ? 'selected' : ''; ?>>Feet</option>
                <option value="centimeters" <?php echo ($filter_size_unit === 'centimeters') ? 'selected' : ''; ?>>Centimeters</option>
                <option value="meters" <?php echo ($filter_size_unit === 'meters') ? 'selected' : ''; ?>>Meters</option>
            </select>
            <label class="io_fld_title" for="<?php echo $this->get_field_id('filter_size_min')?>">Min:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('filter_size_min')?>"
                   name="<?php echo $this->get_field_name('filter_size_min')?>" style="width:50px"
                   type="number" value= "<?php echo esc_attr($filter_size_min); ?>"/>
            <br>
            <label class="io_fld_title" for="<?php echo $this->get_field_id('filter_size_max')?>">Max:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('filter_size_max')?>"
                   name="<?php echo $this->get_field_name('filter_size_max')?>" style="width:50px"
                   type="number" value="<?php echo esc_attr($filter_size_max); ?>"/>
        </div>

        <script>
            jQuery( document ).ready(function() {
                if ( jQuery("#<?php echo esc_attr($this->get_field_id('filter_price')); ?>").is(':checked') ) {
                    jQuery("#io_filter_price_select").show();
                } else {
                    jQuery("#io_filter_price_select").hide();
                }
                jQuery("#<?php echo esc_attr($this->get_field_id('filter_price')); ?>").change(function() {
                    if ( jQuery(this).is(':checked') ) {
                        jQuery("#io_filter_price_select").show();
                    } else {
                        jQuery("#io_filter_price_select").hide();
                    }
                });

                if ( jQuery("#<?php echo esc_attr($this->get_field_id('filter_size')); ?>").is(':checked') ) {
                    jQuery("#io_filter_size_options").show();
                } else {
                    jQuery("#io_filter_size_options").hide();
                }
                jQuery("#<?php echo esc_attr($this->get_field_id('filter_size')); ?>").change(function() {
                    if ( jQuery(this).is(':checked') ) {
                        jQuery("#io_filter_size_options").show();
                    } else {
                        jQuery("#io_filter_size_options").hide();
                    }
                });
            });
        </script>
        <br>
        <hr>
        <div id="custom_filter_group_container"></div>
        <h3>Create Custom Group</h3>
        <div style = "display:inline-flex">
            <input type="text" id="customGroupInput" placeholder="Group Name...">
            <button style="width:100px;margin-left:5px" onclick="create_custom_group(event)">Create</button>
        </div>
        <input type="text" style="display:none" id="<?php echo $this->get_field_id("customGroupsData") ?>" name="<?php echo $this->get_field_name("customGroupsData") ?>">
        <script>
            // Create a separate function for event listener assignment
            // Since we pass in group name to this function it will always be in scope for the event listener.
            var assignEventListener = function(inputElement, group_name) {
                inputElement.addEventListener('input', function(e) {
                    let split_input_element_val = inputElement.value.split("_");
                    let filter_name = split_input_element_val[0];
                    let group_id = split_input_element_val[1];
                    let hidden_input_val = jQuery("#<?php echo $this->get_field_id("customGroupsData") ?>").val();
                    if(hidden_input_val){
                        try{
                            /* Individual inputs can be turned on and off are saved as either 1(on) or 0(off).*/
                            hidden_input_val_obj = JSON.parse(hidden_input_val);
                            /* If the group already exists in object, set the value for this input. */
                            if(hidden_input_val_obj.hasOwnProperty(group_name)){
                                hidden_input_val_obj[group_name][filter_name] = inputElement.checked ? 1 : 0;
                            }else{
                                /* If the group does not exist in object, add it and set the input. */
                                hidden_input_val_obj[group_name] = {
                                    [filter_name] : inputElement.checked ? 1 : 0,
                                    id : group_id
                                };
                            }
                            jQuery("#<?php echo $this->get_field_id("customGroupsData") ?>").val(JSON.stringify(hidden_input_val_obj));
                        }catch(e) {}
                    }else{
                        /* For the very first time this feature is used, the hidden_input_val will be an empty string.
                        We need to make a new object and add the new group and input that fired this event.
                        From this point on the hidden_input_val will be either an empty object or an object with groups in it. */
                        hidden_input_val_obj = {};
                        hidden_input_val_obj[group_name] = {
                            [filter_name] : inputElement.checked ? 1 : 0,
                            id : group_id
                        };
                        jQuery("#<?php echo $this->get_field_id("customGroupsData") ?>").val(JSON.stringify(hidden_input_val_obj));
                    }
                });
            };
        </script>
        <div id="customGroupsContainer">
            <?php
            $checkboxes_only_JSON = "''";
            $checkboxes_only_ARR = Array();
            foreach($filter_data as $name => $data) {
                if($data->type == "checkbox"){
                    $checkboxes_only_ARR[$name] = $data;
                }
            }
            if(count($checkboxes_only_ARR) > 0){
                $checkboxes_only_JSON = json_encode($checkboxes_only_ARR);
            }
            if(!empty($customGroupsData_obj)) {
                foreach ($customGroupsData_obj as $group_name => $group_data) {
                    ?>
                    <div id="io_custom_group_<?php echo $group_data->id ?>" style="width: 95%; border: 1px solid rgb(179, 179, 179); margin: 5px; padding: 5px;">
                        <h6><?php echo $group_name ?></h6>
                        <?php
                            foreach($checkboxes_only_ARR as $checkbox_name => $checkbox_data){
                                $checked = '';
                                $input_id_with_group_id = $checkbox_data->variable_name."_".$group_data->id;
                                if( isset($group_data->{$checkbox_data->variable_name}) && $group_data->{$checkbox_data->variable_name} == 1){
                                    $checked = 'checked="checked"';
                                }
                                ?>
                                <input class="widefat" id="customOptField_<?php echo $input_id_with_group_id ?>"
                                       name="customOptField_<?php echo $input_id_with_group_id ?>" type="checkbox"
                                       value="<?php echo $input_id_with_group_id ?>" <?php echo $checked ?> >
                                <label for="customOptField_<?php echo $input_id_with_group_id ?>"><?php echo $checkbox_name ?></label>
                                <br>
                            <?php }
                        ?>
                    <p style="text-align: right;margin: 0px;"><a id="customGroupRemove_" style="cursor:pointer" onclick="removeCustomGroup(this)">Remove</a></p>
                    </div>
                    <script>
                        jQuery("[id^='customOptField_customfield-'][id$='<?php echo $group_data->id ?>']").each(function(index, element){
                            assignEventListener(element, "<?php echo $group_name ?>")
                        });
                    </script>
                    <?php
                }
            }
            ?>
        </div>
        <script>
            <?php
            echo "var checkboxes_only = ".$checkboxes_only_JSON.";";
            ?>
            jQuery("#<?php echo $this->get_field_id("customGroupsData") ?>").val('<?php echo $customGroupsData ?>');

            function removeCustomGroup(element){
                /* find the text of the h2 element as that is the group name */
                let group_name = element.parentElement.parentElement.firstElementChild.innerText

                let hidden_input_val = jQuery("#<?php echo $this->get_field_id("customGroupsData") ?>").val();
                if(hidden_input_val){
                    try{
                        hidden_input_val_obj = JSON.parse(hidden_input_val);
                        if(hidden_input_val_obj.hasOwnProperty(group_name)){
                            delete hidden_input_val_obj[group_name];
                            jQuery("#<?php echo $this->get_field_id("customGroupsData") ?>").val(JSON.stringify(hidden_input_val_obj));
                            jQuery("#<?php echo $this->get_field_id("customGroupsData") ?>").trigger('change');
                        }
                    }catch(e) {}
                }
                element.parentElement.parentElement.remove();
            }

            function create_custom_group(event){
                event.preventDefault();
                group_name = jQuery("#customGroupInput").val()
                if(group_name && checkboxes_only) {
                    let unique_number = 0
                    do {
                        unique_number = getRndInteger(0, 999999)
                    } while (jQuery("#io_custom_group_" + unique_number).length > 0);

                    let container = document.createElement("div");
                    container.setAttribute("id", "io_custom_group_" + unique_number);
                    container.style.width = "95%";
                    container.style.border = "1px solid #b3b3b3";
                    container.style.margin = "5px";
                    container.style.padding = "5px";
                    let h6 = document.createElement("H6");
                    let h6_txt = document.createTextNode(group_name);
                    h6.appendChild(h6_txt);
                    container.appendChild(h6);
                    for (const property in checkboxes_only) {
                        variable_name = checkboxes_only[property]["variable_name"];

                        inputElement = document.createElement("input");

                        inputElement.setAttribute("class", "widefat");
                        inputElement.setAttribute("id", "customOptField_"+variable_name+"_"+unique_number);
                        inputElement.setAttribute("name", "customOptField_"+variable_name+"_"+unique_number);
                        inputElement.setAttribute("type", "checkbox");
                        inputElement.setAttribute("value", variable_name+"_"+unique_number);

                        // Call the assignEventListener function to assign the listener
                        // Pass in group_name so the correct group name is always in scope.
                        assignEventListener(inputElement, group_name);

                        labelElement = document.createElement("label");
                        labelElement.setAttribute("for", "customOptField_"+variable_name+"_"+unique_number);

                        labelText = property;
                        labelElement.textContent = labelText;

                        container.appendChild(inputElement);
                        container.appendChild(labelElement);
                        container.appendChild(document.createElement("br"))
                    }

                    let p = document.createElement("p");
                    p.style.textAlign = "right";
                    p.style.margin = "0px";

                    let a = document.createElement("a");
                    a.id = "customGroupRemove_" + unique_number;
                    a.style.cursor = "pointer";
                    a.textContent = "Remove";
                    a.addEventListener("click", function() {
                        removeCustomGroup(a);
                    });

                    p.appendChild(a);
                    container.appendChild(p);
                    document.getElementById("customGroupsContainer").appendChild(container);
                }

            }
            function getRndInteger(min, max) {
                return Math.floor(Math.random() * (max - min) ) + min;
            }
        </script>
        <h3>Style Settings</h3>
        <hr>
        <br>
        <input class="widefat" id="<?php echo $this->get_field_id('filter_scroll')?>"
               name="<?php echo $this->get_field_name('filter_scroll')?>"
               type="checkbox" value="1" <?php echo esc_attr($filter_scroll_checked); ?>/>
        <label for="<?php echo $this->get_field_id('filter_scroll')?>">Have widget scroll with screen</label>
        <br>
        <br>
        <h5>Display Type:</h5>
        <input type="radio" name="<?php echo $this->get_field_name('display_type')?>" id="io_filter_display_horizontal"
               value="vertical" <?php echo $display_vertical_checked; ?>  class="widefat" />
        <label for="io_checkavail_horizontal" class="io_fld_title"><?php _e( "Vertical", 'io' ); ?></label><br>
        <input type="radio" name="<?php echo $this->get_field_name('display_type')?>" id="io_filter_display_horizontal"
               value="horizontal" <?php echo $display_horizontal_checked; ?>  class="widefat" />
        <label for="io_checkavail_horizontal" class="io_fld_title"><?php _e( "Horizontal", 'io' ); ?></label><br>
        <br>
        <label for="io_filter_column_width"><?php _e('Column Width (in pixels)', 'text_domain'); ?></label>
        <input type="number" name="<?php echo $this->get_field_name('column_width')?>" id="io_filter_column_width"
               value="<?php echo esc_attr($column_width) ?>" class="widefat" />
        <br>
        <label for="io_filter_number_of_columns"><?php _e('Number of columns', 'text_domain'); ?></label>
        <input type="number" min="1" name="<?php echo $this->get_field_name('number_of_columns')?>" id="io_filter_number_of_columns"
               value="<?php echo esc_attr($number_of_columns) ?>" class="widefat" />
        <?php
    }
    // Update widget settings
    public function update( $new_instance, $old_instance ) {
        $instance = $new_instance;
        return $instance;
    }
    // Display the widget
    public function widget( $args, $instance ) {
        $filter_data = json_decode(get_option("io_filter_data"));
        // This case means the filter has never had its update function run, so its brand new and never modified.
        // We want availablity and price on by default.
        if(empty($instance)){
            $instance['filter_price'] = 1;
            $instance['filter_availability'] = 1;
            $instance['display_type'] = 'horizontal';
            $instance['search_type'] = "exclusive";
        }
        $display = '';
        if($instance['display_type'] == 'horizontal') $display= 'display:flex; width: 100%; flex-wrap:wrap;';
        $position = '';
        if(isset($instance['filter_scroll']) && $instance['filter_scroll'] == 1) {
            $position = 'position:fixed;';
        }
        $grid_columns = "'";
        for($i=0; $i<$instance['number_of_columns']; ++$i){
            $grid_columns.='a ';
        }
        if($instance['display_type'] == 'horizontal') {
            $details_class = 'io_filter_details_horizontal';
        }else if($instance['display_type'] == 'vertical'){
            $details_class = 'io_filter_details_vertical';
        }
        $grid_columns = trim($grid_columns)."'";
        $search_type = "exclusive";
        if(isset($instance['search_type'])){
            $search_type = $instance['search_type'];
        }
        $search_button_text = "Search";
        if(isset($instance['search_button_text'])){
            $search_button_text = $instance['search_button_text'];
        }
        $reset_button_text = "Reset";
        if(isset($instance['reset_button_text'])){
            $reset_button_text = $instance['reset_button_text'];
        }

        $grid_style = ' style="grid-auto-columns:'.$instance['column_width'].'px'.'; grid-template-areas:'.$grid_columns.'" ';

        echo '<form method="post" id="ioFilterForm" style="'.$display.$position.'" action="">';
        /*
        if($instance['dimensions']){
            echo "dimensions are selected<br>";
        }
        if($instance['circuits']){
            echo "circuits are selected<br>";
        }
        if($instance['space_required']){
            echo "space_required is selected<br>";
        }
        */
        $current_filter_arr = array_filter($instance, function($key){
            return strpos($key, 'optField_') === 0;
        }, ARRAY_FILTER_USE_KEY);
        $complete_display = '';
        $checkboxes_only = '
            <details open class="elementor-widget-heading '.$details_class.'">
                <summary class="elementor-heading-title" style="width:'.$instance['column_width']*$instance['number_of_columns'].'px;'.'">Additional Details</summary>
                <div '.$grid_style.' class="io_filter_options_grid">';
        foreach($filter_data as $data_name => $data) {
            if($current_filter_arr['optField_' . str_replace(" ", "_", $data_name)] == 1){
                $html = "";
                if ($data->type == 'smalltext' || $data->type == 'largetext' || $data->type == 'select') {
                    $html = '<details open class="elementor-widget-heading '.$details_class.'"> <summary class="elementor-heading-title" style="width:'.$instance['column_width']*$instance['number_of_columns'].'px;'.'">' . $data_name . '</summary>';
                    $html .= '<div '.$grid_style.' class="io_filter_options_grid">';
                    foreach ($data->data as $value) {
                        //$value = trim($value);
                        $html .= '<div><input style="margin-right:5px" type="checkbox" name="io_filter_' . str_replace(" ", "_", $data_name) . '_' . str_replace(" ", "_", urlencode($value)) . '" value="' . $filter_data->$data_name->variable_name . '_' . urlencode($value) . '"/>';
                        $html .= '<label class="elementor-widget-text-editor" for="io_filter_' . str_replace(" ", "_", $data_name) . '_' . urlencode($value) . '">' . $value . '</label></div>';
                    }
                    $html .= "</div></details>";
                } else if ($data->type == 'checkbox') {
                    if ($current_filter_arr['optField_' . str_replace(" ", "_", $data_name)] == 1) {
                        $html = '<div><input style="margin-right:5px" type="checkbox" name="io_filter_' . str_replace(" ", "_", $data_name) .'_Yes" value="' . $filter_data->$data_name->variable_name . '_Yes"/>';
                        $html .= '<label class="elementor-widget-text-editor" for="io_filter_' . str_replace(" ", "_", $data_name) . '_Yes">' . $data_name . '</label></div>';
                    }
                    $checkboxes_only.=$html;
                    $html = "";
                }
                if (!empty($html)) {
                    $complete_display.=$html;
                }
            }
        }
        //Build custom grouping of checkbox inputs if any are set.
        $custom_groups_html = "";
        if(!empty($instance["customGroupsData"])){
            $custom_group_obj = json_decode($instance["customGroupsData"]);
            $all_checkboxes = array();
            foreach($filter_data as $data_name => $data) {
                if ($data->type == 'checkbox') {
                    $all_checkboxes[$data->variable_name] = $data_name;
                }
            }
            foreach($custom_group_obj as $group_name => $group_data){
                $outer_details = "";
                foreach($group_data as $group_datum_name => $group_datum){
                    $inner_input = "";
                    if($group_datum_name != "id" && $group_datum == 1){
                        $checkbox_name = $all_checkboxes[$group_datum_name];
                        $inner_input .= '<div><input style="margin-right:5px" type="checkbox" name="io_filter_' . str_replace(" ", "_", $checkbox_name) .'_Yes" value="' . $filter_data->$checkbox_name->variable_name . '_Yes"/>';
                        $inner_input .= '<label class="elementor-widget-text-editor" for="io_filter_' . str_replace(" ", "_", $checkbox_name) . '_Yes">' . $checkbox_name . '</label></div>';

                        if($outer_details == ""){
                            $outer_details = '<details open class="elementor-widget-heading '.$details_class.'"> <summary class="elementor-heading-title" style="width:'.$instance['column_width']*$instance['number_of_columns'].'px;'.'">' . $group_name . '</summary>';
                            $outer_details .= '<div '.$grid_style.' class="io_filter_options_grid">';
                        }
                        $outer_details .= $inner_input;
                    }
                }
                if($outer_details != ""){
                    $custom_groups_html .= $outer_details;
                    $custom_groups_html .= "</div></details>";
                }
            }
        }
        $complete_display .= $custom_groups_html;

        if($checkboxes_only != '
            <details open class="elementor-widget-heading '.$details_class.'">
                <summary class="elementor-heading-title" style="width:'.$instance['column_width']*$instance['number_of_columns'].'px;'.'">Additional Details</summary>
                <div '.$grid_style.' class="io_filter_options_grid">'){
            $checkboxes_only .= "</div>";
            $checkboxes_only .= "</details>";
            $complete_display .= $checkboxes_only;
        }

        $size_filter_html = "";
        if (isset($instance['filter_size']) && $instance['filter_size'] == 1) {
            $size_filter_html .= '<details open class="elementor-widget-heading '.$details_class.'">';
            $size_filter_summary = '<summary class="elementor-heading-title" style="width:'.$instance['column_width']*$instance['number_of_columns'].'px;'.'">';
            $summary_text = 'Filter by Size';
            $size_filter_content = '<div class="elementor-widget-text-editor">';
            $size_filter_script = '<script>
                var lowerLengthSlider = document.querySelector("#io_filter_length_lower_slider"),
                upperLengthSlider = document.querySelector("#io_filter_length_upper_slider"),
                lowerLengthInput = document.querySelector("#io_filter_length_lower"),
                upperLengthInput = document.querySelector("#io_filter_length_upper");
                if(lowerLengthSlider && upperLengthSlider){
                    set_oninput_for_upper_and_lower_sliders(lowerLengthSlider, upperLengthSlider, "length");
                    set_oninput_for_upper_and_lower_text_inputs(lowerLengthInput, upperLengthInput, "length");
                    
                }
                var lowerWidthSlider = document.querySelector("#io_filter_width_lower_slider"),
                upperWidthSlider = document.querySelector("#io_filter_width_upper_slider"),
                lowerWidthInput = document.querySelector("#io_filter_width_lower"),
                upperWidthInput = document.querySelector("#io_filter_width_upper");
                if(lowerWidthSlider && upperWidthSlider){
                    set_oninput_for_upper_and_lower_sliders(lowerWidthSlider, upperWidthSlider, "width")
                    set_oninput_for_upper_and_lower_text_inputs(lowerWidthInput, upperWidthInput, "width")
                }
                var lowerHeightSlider = document.querySelector("#io_filter_height_lower_slider"),
                upperHeightSlider = document.querySelector("#io_filter_height_upper_slider"),
                lowerHeightInput = document.querySelector("#io_filter_height_lower"),
                upperHeightInput = document.querySelector("#io_filter_height_upper");
                if(lowerHeightSlider && upperHeightSlider){
                    set_oninput_for_upper_and_lower_sliders(lowerHeightSlider, upperHeightSlider, "height");
                    set_oninput_for_upper_and_lower_text_inputs(lowerHeightInput, upperHeightInput, "height");
                    
                }
                var lowerAreaSlider = document.querySelector("#io_filter_area_lower_slider"),
                upperAreaSlider = document.querySelector("#io_filter_area_upper_slider"),
                lowerAreaInput = document.querySelector("#io_filter_area_lower"),
                upperAreaInput = document.querySelector("#io_filter_area_upper");
                if(lowerAreaSlider && upperAreaSlider){
                    set_oninput_for_upper_and_lower_sliders(lowerAreaSlider, upperAreaSlider, "area");
                    set_oninput_for_upper_and_lower_text_inputs(lowerAreaInput, upperAreaInput, "area");
                    
                }
                
                function set_oninput_for_upper_and_lower_sliders(lowerSlider, upperSlider, text_name){
                    upperSlider.oninput = function() {
                        lowerVal = parseInt(lowerSlider.value);
                        upperVal = parseInt(upperSlider.value);
                    
                        jQuery("#io_filter_"+text_name+"_upper").val(upperVal);
                        if (upperVal < lowerVal) {
                            lowerSlider.value = upperVal;
                            jQuery("#io_filter_"+text_name+"_lower").val(upperVal);
                
                            if (lowerVal == lowerSlider.min) {
                                upperSlider.value;
                            }
                        }
                    };
                    lowerSlider.oninput = function() {
                        lowerVal = parseInt(lowerSlider.value);
                        upperVal = parseInt(upperSlider.value);
                    
                        jQuery("#io_filter_"+text_name+"_lower").val(lowerVal);
                        if (lowerVal > upperVal) {
                            upperSlider.value = lowerVal;
                            jQuery("#io_filter_"+text_name+"_upper").val(lowerVal);
                            if (upperVal == upperSlider.max) {
                                lowerSlider.value = parseInt(upperSlider.max);
                            }
                        }
                    };
                }
                
                function set_oninput_for_upper_and_lower_text_inputs(lowerInput, upperInput, text_name){
                    let lowerSlider = document.querySelector("#io_filter_"+text_name+"_lower_slider");
                    let upperSlider = document.querySelector("#io_filter_"+text_name+"_upper_slider");
                    upperInput.onchange = function() {
                        if(parseInt(upperInput.value) > parseInt(upperInput.max)){
                            upperInput.value = upperInput.max
                        }else if(parseInt(upperInput.value) < parseInt(upperInput.min)){
                            upperInput.value = upperInput.min
                        }
                        
                        input_value = upperInput.value;
                        
                        upperSlider.value = upperInput.value;
                        
                        if (parseInt(upperSlider.value) < parseInt(lowerSlider.value)) {
                            lowerSlider.value = upperSlider.value;
                            lowerInput.value = upperInput.value;
                            if (lowerSlider.value == lowerSlider.min) {
                                upperSlider.value = parseInt(lowerSlider.min);;
                            }
                        }
                    };
                    lowerInput.onchange = function() {
                        if(parseInt(lowerInput.value) < parseInt(lowerInput.min)){
                            lowerInput.value = lowerInput.min
                        }else if(parseInt(lowerInput.value) > parseInt(lowerInput.max)){
                            lowerInput.value = lowerInput.max
                        }
                        
                        lowerSlider.value = lowerInput.value;
                        
                        if (parseInt(lowerSlider.value) > parseInt(upperSlider.value)) {
                            upperSlider.value = lowerSlider.value;
                            upperInput.value = lowerInput.value;
                            if (upperSlider.value == upperSlider.max) {
                                lowerSlider.value = parseInt(upperSlider.max);
                            }
                        }
                    };
                }
            </script>';

            if($instance['filter_size_mode'] == "length-width-height"){
                $size_filter_content .= '
                <div id="io_filter_size_toggle_container">
                    <input style="margin-right:5px" type="checkbox" id="io_filter_size_toggle" name="io_filter_size_toggle" value="io_filter_size_toggle">
                    <label class="elementor-widget-text-editor" for="io_filter_size_toggle">Filter by size</label>
                </div>
                <div id="io_filter_size_container">
                    <div>
                        <span style="display:block">
                            Length between <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_length_lower" id="io_filter_length_lower"></input> '.$instance['filter_size_unit'].' and <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_length_upper" id="io_filter_length_upper"></input> '.$instance['filter_size_unit'].'.
                        </span>
                        <div class="multi-range">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_min'].'" id="io_filter_length_lower_slider">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_max'].'" id="io_filter_length_upper_slider">
                        </div>
                    </div>
                    <div>
                        <span style="display:block">
                            Width between <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_width_lower" id="io_filter_width_lower"></input> '.$instance['filter_size_unit'].' and <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_width_upper" id="io_filter_width_upper"></input> '.$instance['filter_size_unit'].'.
                        </span>
                        <div class="multi-range">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_min'].'" id="io_filter_width_lower_slider">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_max'].'" id="io_filter_width_upper_slider">
                        </div>
                    </div>
                    <div>
                        <span style="display:block">
                            Height between <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_height_lower" id="io_filter_height_lower"></input> '.$instance['filter_size_unit'].' and <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_height_upper" id="io_filter_height_upper"></input> '.$instance['filter_size_unit'].'.
                        </span>
                        <div class="multi-range">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_min'].'" id="io_filter_height_lower_slider">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_max'].'" id="io_filter_height_upper_slider">
                        </div>
                    </div>
                </div>
                <script>
                    jQuery(document).ready(function (){
                        jQuery("#io_filter_length_lower").val(jQuery("#io_filter_length_lower_slider").val());
                        jQuery("#io_filter_length_upper").val(jQuery("#io_filter_length_upper_slider").val());
                        
                        jQuery("#io_filter_width_lower").val(jQuery("#io_filter_width_lower_slider").val());
                        jQuery("#io_filter_width_upper").val(jQuery("#io_filter_width_upper_slider").val());
                        
                        jQuery("#io_filter_height_lower").val(jQuery("#io_filter_height_lower_slider").val());
                        jQuery("#io_filter_height_upper").val(jQuery("#io_filter_height_upper_slider").val());
                    });
                </script>';
            }else if($instance['filter_size_mode'] == "length-width"){
                $size_filter_content .= '
                <div>
                    <div id="io_filter_size_toggle_container">
                        <input style="margin-right:5px" type="checkbox" id="io_filter_size_toggle" name="io_filter_size_toggle" value="io_filter_size_toggle">
                        <label class="elementor-widget-text-editor" for="io_filter_size_toggle">Filter by size</label>
                    </div>
                    <div id="io_filter_size_container">
                            <span style="display:block">
                                Length between <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_length_lower" id="io_filter_length_lower"></input> '.$instance['filter_size_unit'].' and <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_length_upper" id="io_filter_length_upper"></input> '.$instance['filter_size_unit'].'.
                            </span>
                            <div class="multi-range">
                                <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_min'].'" id="io_filter_length_lower_slider">
                                <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_max'].'" id="io_filter_length_upper_slider">
                            </div>
                        <div>
                            <span style="display:block">
                                Width between <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_width_lower" id="io_filter_width_lower"></input> '.$instance['filter_size_unit'].' and <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_width_upper" id="io_filter_width_upper"></input> '.$instance['filter_size_unit'].'.
                            </span>
                            <div class="multi-range">
                                <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_min'].'" id="io_filter_width_lower_slider">
                                <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_max'].'" id="io_filter_width_upper_slider">
                            </div>
                        </div>
                    </div>
                </div>
                <script>
                    jQuery(document).ready(function (){
                        jQuery("#io_filter_length_lower").val(jQuery("#io_filter_length_lower_slider").val());
                        jQuery("#io_filter_length_upper").val(jQuery("#io_filter_length_upper_slider").val());
                        
                        jQuery("#io_filter_width_lower").val(jQuery("#io_filter_width_lower_slider").val());
                        jQuery("#io_filter_width_upper").val(jQuery("#io_filter_width_upper_slider").val());
                    });
                </script>';
            }else if($instance['filter_size_mode'] == "area"){
                $size_filter_content .= '
                <div>
                    <div id="io_filter_size_toggle_container">
                        <input style="margin-right:5px" type="checkbox" id="io_filter_size_toggle" name="io_filter_size_toggle" value="io_filter_size_toggle">
                        <label class="elementor-widget-text-editor" for="io_filter_size_toggle">Filter by size</label>
                    </div>
                    <div id="io_filter_size_container">
                        <span style="display:block">
                            Area between <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_area_lower" id="io_filter_area_lower"></input> sq '.$instance['filter_size_unit'].' and <input type="number" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" class="io_filter_slider_text_input" name="io_filter_area_upper" id="io_filter_area_upper"></input> sq '.$instance['filter_size_unit'].'.
                        </span>
                        <div class="multi-range">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_min'].'" id="io_filter_area_lower_slider">
                            <input type="range" min="'.$instance['filter_size_min'].'" max="'.$instance['filter_size_max'].'" value="'.$instance['filter_size_max'].'" id="io_filter_area_upper_slider">
                        </div>
                    </div>
                </div>
                <script>
                    jQuery(document).ready(function (){
                        jQuery("#io_filter_area_lower").val(jQuery("#io_filter_area_lower_slider").val());
                        jQuery("#io_filter_area_upper").val(jQuery("#io_filter_area_upper_slider").val());
                    });
                </script>';
            }

            $size_filter_summary .= $summary_text."</summary>";
            $size_filter_html .= $size_filter_summary.$size_filter_content.$size_filter_script."</div></details>";
        }

        $availability_and_price_filter_html = "";
        if($instance['filter_price'] == 1 || $instance['filter_availability'] == 1){
            $availability_and_price_filter_html .= '<details open class="elementor-widget-heading '.$details_class.'">';
            $availability_and_price_filter_summary = '<summary class="elementor-heading-title" style="width:'.$instance['column_width']*$instance['number_of_columns'].'px;'.'">';
            $summary_text = '';
            $availability_and_price_filter_content = '<div class="elementor-widget-text-editor">';
            if($instance['filter_price'] == 1){
                $summary_text = 'Pricing';
                if($instance['filter_price_mode'] == '1hr'){
                    $availability_and_price_filter_content .= '
                        <div>
                            <p style="margin-right: 5px;">Price range per hour: </p>
                            <label style="margin-right: 5px" for="io_filter_price_min">Between</label><input type="number" step=".01" name="io_filter_price_min" class="io_filter_price" id="io_filter_price_min"/>
                            <label style="margin-right: 5px" for="io_filter_price_max">And</label><input type="number" step=".01" name="io_filter_price_max" class="io_filter_price" id="io_filter_price_max"/>
                        </div>
                        
                    ';
                }else if($instance['filter_price_mode'] == 'userInput'){
                    $availability_and_price_filter_content .= '
                        <div>
                            <p style="margin-right: 5px;">Price range per <span style="cursor:pointer; color:blue; text-decoration:underline;" onclick=checkAvailDateClick()>time selected</span>: </p>
                            <label style="margin-right: 5px" for="io_filter_price_min">Between</label><input type="number" step=".01" name="io_filter_price_min" class="io_filter_price" id="io_filter_price_min"/>
                            <label style="margin-right: 5px" for="io_filter_price_max">And</label><input type="number" step=".01" name="io_filter_price_max" class="io_filter_price" id="io_filter_price_max"/>
                        </div>
                        
                    ';
                }
            }
            if($instance['filter_availability'] == 1){
                if(empty($summary_text)){
                    $summary_text = 'Availability';
                }else{
                    $summary_text .= ' and Availability';
                    $availability_and_price_filter_content .= '<br>';
                }
                $availability_and_price_filter_content .= '
                        <div>
                            <input style="margin-right:5px" name="io_filter_availability" id="io_filter_availability" type="checkbox" value="1"/>
                            <label for="io_filter_availability">Only show items available for your <span style="cursor:pointer; color:blue; text-decoration:underline;" onclick=checkAvailDateClick()>selected time</span></label>
                        </div>
                    ';
            }
            $availability_and_price_filter_summary .= $summary_text."</summary>";
            $availability_and_price_filter_html .= $availability_and_price_filter_summary;
            $availability_and_price_filter_html .= $availability_and_price_filter_content."</div></details>";
        }
        echo $complete_display.$availability_and_price_filter_html.$size_filter_html;



        echo '<br>
            <div style = "margin-left:auto;display:flex;">
                <div style="margin-right: 5px" class="elementor-widget-button">
                    <input type="submit" class="elementor-button elementor-animation-grow elementor-size-sm" name="" value="'.$search_button_text.'"/>
                </div>
                <div class="elementor-widget-button">
                    <button type="button" class="elementor-button elementor-animation-grow elementor-size-sm" name="io_filter_clear">'.$reset_button_text.'</button>
                </div>
            </div>
            </form>
            <span style="display:none !important;" id="io_filter_search_type" data="'.$search_type.'"></span>
            <script>
				var io_filter_dir = "'.$_SERVER['SCRIPT_NAME'].'";
				var io_filter_server_name = "'.$_SERVER['SERVER_NAME'].'";
				var io_filter_server_scheme = "'.$_SERVER['REQUEST_SCHEME'].'";
                jQuery(document).ready(function () {
                    jQuery("#ioFilterForm").submit(function (event) {
                        event.preventDefault();
                        let seralized_filter_data = jQuery(this).serializeArray();
                        seralized_filter_data = remove_invalid_inputs(seralized_filter_data);
                        if(getCookie("io_SelectedFilters") == ""){
                            selected_filter_cookie = {};
                        }else{
                            selected_filter_cookie = JSON.parse(getCookie("io_SelectedFilters"));
                        }
                        if(seralized_filter_data.length){
                            if(check_if_io_category_page()){
                                filter_cookie_key = jQuery(".category_id").text();
                                selected_filter_cookie[filter_cookie_key] = seralized_filter_data;
                            }else if(check_if_io_featured_widget()){
                                selected_filter_cookie["fpw"] = seralized_filter_data;
                            }
                            setCookie("io_SelectedFilters", JSON.stringify(selected_filter_cookie), 14);
                            let featured_widget_options = build_featured_widget_options();
                            if(jQuery("#io_filter_availability").length && jQuery("#io_filter_availability").is(":checked")){
                                let times = getAvailTimes()
                                featured_widget_options["start_date"] = times[0]
                                featured_widget_options["start_time"] = times[1]
                                featured_widget_options["duration"] = times[2]
                            }
                            let search_type = jQuery("#io_filter_search_type").attr("data");
                            //url = window.location.href+"?"+jQuery(this).serialize()+"&io_filter_submit=Submit";
                            let url = io_filter_server_scheme+"://"+io_filter_server_name+io_filter_dir.replace("index.php", "wp-content/plugins/inflatableoffice/website_filter.php?")
                                      + jQuery(this).serialize()+"&io_filter_submit=Submit"
                                      + "&show_price="+featured_widget_options["show_price"]
                                      + "&view_product_hover="+featured_widget_options["view_product_hover"]
                                      + "&add_to_cart="+featured_widget_options["add_to_cart"]
                                      + "&width="+featured_widget_options["width"]
                                      + "&name=" + encodeURIComponent(io_pagename)
                                      + "&start_date="+featured_widget_options["start_date"]
                                      + "&start_time="+featured_widget_options["start_time"]
                                      + "&duration="+featured_widget_options["duration"]
                                      + "&category="+featured_widget_options["category"]
                                      + "&page_rental_ids="+featured_widget_options["page_rental_ids"]
                                      + "&io_filter_search_type="+search_type;
                            jQuery.ajax({
                                type: "POST",
                                url: url,
                                dataType: "html",
                                success: display_filtered_results
                            })
                        }
                        
                    })
                    
                    jQuery("button[name=io_filter_clear]").click(function(){
                        if(check_if_io_category_page()){
                            var page_key = jQuery(".category_id").text();
                        }else if(check_if_io_featured_widget()){
                            var page_key = "fpw"
                        }
                        let selected_filters = {};
                        try{
                            selected_filters = JSON.parse(getCookie("io_SelectedFilters"));
                        }catch(e){}
                        delete selected_filters[page_key]
                        setCookie("io_SelectedFilters",JSON.stringify(selected_filters), 14);
                        window.location.replace(window.location.href);
                    });
                    jQuery("#io_filter_size_toggle").on("change", function() {
                        if ( jQuery(this).is(":checked") ) {
                            jQuery("#io_filter_size_container").show();
                            jQuery(".io_filter_slider_text_input").prop( "disabled", false );
                        } else {
                            jQuery("#io_filter_size_container").hide();
                            jQuery(".io_filter_slider_text_input").prop( "disabled", true );
                        }
                    });
                    try{
						set_selected_filters_from_cookie();
					}catch(e){
					    console.log(e);
					}
                    
                })
                function display_filtered_results(data){
                    jQuery("div[data-elementor-type=\"wp-page\"] .elementor-section").filter(check_if_io_featured_widget).each(function(){
                        let widget_container = jQuery(this).find(".elementor-widget-wp-widget-widget_featured .elementor-widget-container");
                        jQuery(widget_container).empty();
                        jQuery(widget_container).append(data);
                    });
                    if(check_if_io_category_page()){
                        let widget_container = jQuery(document).find(".io_catdiv2");
                        jQuery(widget_container).empty();
                        //data = data.replace("io_mm_item", "io_item2_list");
                        jQuery(widget_container).css("display", "block");
                        jQuery(widget_container).append(data);
                    }
                }
                function check_if_io_featured_widget() {
                    if(jQuery(".elementor-widget-wp-widget-widget_featured").length !== 0){
                        return true;
                    }
                    return false;
                }
                function check_if_io_category_page() {
                    if(jQuery(".io_catdiv2").length !== 0){
                        return true;
                    }
                    return false;
                }
                function build_featured_widget_options(){
                    let options = {
                        show_price: "", 
                        view_product_hover: "", 
                        scrolling_view: "", 
                        add_to_cart: "", 
                        width: "", 
                        categories: "",
                        start_date: "",
                        duration: "",
                        start_time: "",
                        price_min: "",
                        price_max: "",
                        page_rental_ids: ""
                    }
                    if(jQuery(".page-content .rentNameIO_price").is(":visible")) options["show_price"] = 1;
                    if(jQuery(".page-content .view-product-button").is(":visible")) options["view_product_hover"] = 1;
                    if(jQuery(".page-content .rentNameIO_button").is(":visible")) options["add_to_cart"] = 1;
                    if(jQuery(".category_id").length !==0 ) {
                        // Want to get just the name of the category without anything else like "for rent".
                        options["category"] = jQuery(".category_id").text();
                    }          
                    options["width"] = jQuery(".page-content .io_mm_item").width()+20;
                    if(!options["width"]) options["width"] = 350;
                    let page_rental_ids = "";
                    jQuery(".io_item2_list_inner .item_rentalid").each(function(){
                        page_rental_ids += jQuery(this).text()+",";
                    })
                    options["page_rental_ids"] = page_rental_ids;
                    return options;
                }
                function set_selected_filters_from_cookie(){
                    let selected_filters = {};
                    try{
                        selected_filters = JSON.parse(getCookie("io_SelectedFilters"));
                    }catch(e){}
                   
                    if(check_if_io_category_page()){
                        var page_key = jQuery(".category_id").text();
                    }else if(check_if_io_featured_widget()){
                        var page_key = "fpw";
                    }
                    for (const [key, filters] of Object.entries(selected_filters)) {
                        if(key == page_key){
                            filters.forEach(function(filter) {
                               let io_filter_input = jQuery("#ioFilterForm input[name=\""+filter["name"]+"\"]");
                               if(io_filter_input.attr("type") != "checkbox"){
                                    io_filter_input.val(filter["value"]);
                                    io_filter_input.trigger("change");
                               }else{
                                    io_filter_input.prop("checked", true);
                                    io_filter_input.trigger("change");
                               } 
                            });
                            if(!jQuery("#io_filter_size_toggle").is(":checked")){
						        jQuery(".io_filter_slider_text_input").prop( "disabled", true );
						    }
                            jQuery("#ioFilterForm input[name=io_filter_submit]").first().click();
                            break;
                        }
                    } 
                }
                function remove_invalid_inputs(filter_data){
                    let inputs_to_remove = [];
                    filter_data.forEach(function (filter, index){
                        if(filter["value"] === ""){
                            inputs_to_remove.push(index)
                        }
                    });
                    if(inputs_to_remove.length > 0){
                        for (var i = inputs_to_remove.length -1; i >= 0; i--){
                            filter_data.splice(inputs_to_remove[i],1);
                        }
                    }
                    return filter_data;
                }
            </script>';
    }
}

