<?php

$this->renderPartial('//snippets/headerGallery');
$cs = Yii::app()->getClientScript();

$cs->registerCssFile('/bower_components/select2/dist/css/select2.min.css');
$cs->registerCssFile('/css/bootstrap/css/bootstrap-theme.min.css');


$cs->registerScriptFile('/bower_components/jquery/dist/jquery.min.js');
$cs->registerScriptFile('/bower_components/select2/dist/js/select2.min.js');
$cs->registerScriptFile('/bower_components/jquery-validation/dist/jquery.validate.min.js');
$cs->registerScriptFile('/css/bootstrap/js/bootstrap.min.js');

?>

<div class="wrapper content-wrapper sto-filter">
    <div class="col-wrapper">
        <div class="col10">
            <h1><?php echo CHtml::encode($this->pageName)?></h1>

            <div class="text-content">
                <?php echo $content ?>
            </div>

            <form id="select-filter-form">
                <div class="row">
                    <div class="col3">
                        <select id="brand" name="StoFilter[brand]">
                            <option class="default" disabled selected>Марка</option>
                            <?php foreach($brands as $brand):?>
                                <option value="<?= $brand->brand ?>"><?= $brand->brand ?></option>
                            <?php endforeach;?>
                        </select>
                    </div>
                    <div class="col3">
                        <select id="model" disabled name="StoFilter[model]">
                            <option  class="default" disabled selected>Модель</option>
                        </select>
                    </div>
                    <div class="col3">
                        <select id="engine" disabled name="StoFilter[engine]">
                            <option  class="default" disabled selected>Двигатель</option>
                        </select>
                    </div>

                </div>
                <div class="row">
                    <div class="col3">
                        <select id="drive_unit" disabled name="StoFilter[drive_unit]">
                            <option  class="default" disabled selected>Привод</option>
                        </select>
                    </div>
                    <div class="col3">
                        <select id="transmission" disabled name="StoFilter[transmission]">
                            <option  class="default" disabled selected>Коробка</option>
                        </select>
                    </div>
                    <div class="col3">
                        <select id="fuel_type" disabled name="StoFilter[fuel_type]">
                            <option  class="default" disabled selected>Тип топлива</option>
                        </select>
                    </div>

                </div>
                <div class="row">
                    <div class="col3">
                        <select id="mileage" disabled name="mileage">
                            <option  class="default" disabled selected>Пробег</option>
                        </select>
                    </div>
                </div>
                <input type="hidden" id="sto_filter_id" name="sto_filter_id" value="">
            </form>


            <div class="row">
                <div class="to-table">


                </div>
            </div>


        </div>
        <div class="col2">
            <p class="section-title"><?php echo Yii::t('site','Есть вопросы?');?></p>

            <div class="text-content">
                <?php echo Yii::t('site','Обращайтесь к вашему персональному консультанту (акции)!');?>
            </div>
            <?php $this->renderPartial('//snippets/sidebarContacts');?>
        </div>
    </div>
</div>
<script type="text/javascript">
    $('select').select2({
        minimumResultsForSearch: Infinity
    });




    $('#sto-form').validate({
        rules:{
            phone:{
                number: true
            }

        },
        messages:{
            name: "Введите ваше имя",
            phone: {
                required: "Введите ваш новер телефона",
                number:  "Неверный формат"
            },
            email: {
                required: "Введите ваш email",
                email: "Неверный формат"
            }
        }
    });

    $('#sto-form').submit(function(e){
        e.preventDefault();
        var error = $(this).find('input.error').length;
        if(!error){
            var $text = $('.to-table').html();
            var $name = $('#exampleInputName').val();
            var $email = $('#exampleInputEmail').val();
            var $phone = $('#exampleInputPhone').val();
            $.post( "/<?= Yii::app()->language?>/ajaxStoFilter/send", {text:$text, name:$name, phone:$phone, email:$email}, function( data ) {
                console.log(data);
            });
        }
    });



    $('body').on('click', '.active-select', function(){



        $(this).siblings('select').find('.default').attr('selected','selected').trigger('change');

    });

    var insertOptions = function(result, id){

        var select =  $("#"+id);



        select.prop("disabled", false);

        var data_select = select.val();

        var options = select.find('option').remove();

        options.splice(1, options.length-1);

        select.append(options);

        for(property in result[id]){


            if(data_select ==property.trim() ){

                select.parent('.col3').append('<div class="active-select">X</div>');

                select.append($('<option>', {
                    value: property,
                    text : property,
                    selected: true
                }));
            } else {

                select.append($('<option>', {
                    value: property,
                    text : property
                }));
            }

        }
    };


    function countFullPrice(){
        var fullPrice = +$('#total-require-price').html() + +$('#priceTotalCars').html();
        $('#full_sto_price').html(fullPrice);

    }


    $('body').on('click', '.optional-row', function(){
       if($(this).prop( "checked" )){
           $(this).attr('checked','checked');


           var price = $(this).parents('tr').find('.optional_row_price').html().replace(' грн.','');

            var priceTotalCars = +$('#priceTotalCars').html();

           priceTotalCars += +price;

           $('#priceTotalCars').html(priceTotalCars);

           countFullPrice();

       } else {
           $(this).removeAttr('checked');

           var price = $(this).parents('tr').find('.optional_row_price').html().replace(' грн.','');

           var priceTotalCars = +$('#priceTotalCars').html();

           priceTotalCars -= +price;

           $('#priceTotalCars').html(priceTotalCars);

           countFullPrice();
       }
    });




    $('select').change(function(){

        if($(this).attr('id') ==='mileage' ){

            var id = $('#sto_filter_id').val();
            var dist = $(this).val();


            $.post( "/<?= Yii::app()->language?>/ajaxStoFilter/renderPriceList", {id:id, dist:dist}, function( data ) {
                $('.to-table').empty();
                $('.to-table').html(data);

                var $requirePrice = 0;
                $(".require-table").find('.require-price').each(function(){
                    var val = $(this).html().replace(' грн.','');
                    $requirePrice += +val;
                });

                $('#total-require-price').html($requirePrice);

                countFullPrice();
            })




        } else {
            var $form = $('#select-filter-form').serialize();

            $.get( "/<?= Yii::app()->language?>/ajaxStoFilter/filter/?"+$form,  function( data ) {

                var result = JSON.parse(data);

                $('body').find('.active-select').remove();

                if(Object.keys(result.model).length){
                    insertOptions(result, 'model');

                }

                if(Object.keys(result.engine).length){
                    insertOptions(result, 'engine');

                }

                if(Object.keys(result.drive_unit).length){
                    insertOptions(result, 'drive_unit');
                }

                if(Object.keys(result.transmission).length){
                    insertOptions(result, 'transmission');
                }

                if(Object.keys(result.fuel_type).length){
                    insertOptions(result, 'fuel_type');
                }

                if((result.mileage !== undefined) && Object.keys(result.mileage).length){
                    insertOptions(result, 'mileage');
                    $('#sto_filter_id').val(result.id);
                }


            });
        }


    });


</script>

