<div class="hpanel">

	<div class="panel-body">

		<?php if($action == 'create'): ?>
		<h3>Agregar nueva versión</h3>
		<?php else: ?>
		<h3>Editar versión</h3>
		<?php endif; ?>
			
		<?php if( count($errors) > 0 ): ?>
		<div class="alert alert-danger">
			<ul>
				<?php foreach($errors->all() as $error): ?>
				<li><?php echo e($error); ?></li>
				<?php endforeach; ?>
			</ul>
		</div>
		<?php endif; ?>

		<form id="form-vehiculo-version" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">

			<input type="hidden" name="_token" value="<?php echo e(csrf_token()); ?>" />

			<input type="hidden" name="id" value="<?php echo e($mock->id); ?>" />

			<div class="form-group">
				<label for="categoria">Modelo</label>
				<select id="modelo" name="modelo" class="form-control" required>
					<option value="">Seleccione</option>
					<?php foreach($catalogo as $categoria => $modelos): ?>
					<optgroup label="<?php echo e($categoria); ?>">
						<?php foreach($modelos as $modelo): ?>
						<option value="<?php echo e($modelo->id); ?>" <?php echo e($modelo->id == $version->id_modelo ? 'selected' : ''); ?>><?php echo e($modelo->nombre); ?></option>
						<?php endforeach; ?>
					</optgroup>
					<?php endforeach; ?>
				</select>
				<div class="help-block with-errors"></div>
			</div>

			<div class="form-group">
				<label for="nombre">Nombre</label>
				<input type="text" id="nombre" name="nombre" value="<?php echo e($mock->nombre); ?>" class="form-control" required/>
				<div class="help-block with-errors"></div>
			</div>
				
			<div class="form-group">
				<div class="col-lg-2 col-xs-12 col-md-2">
					<table class="table table-condensed table-striped">
						<thead>
							<tr>
								<th></th>
								<th>Año</th>
								<th>Catálogo</th>
							</tr>
						</thead>
						<tbody id="catalog_year">
							<?php foreach($lista_anos as $ano): ?>
								<tr>
									<td><input type="checkbox" value="<?php echo e($ano); ?>" name="ano_version[]" <?php echo array_key_exists($ano, $yearsCatalogs_version) ? 'checked' : ''; ?> onclick="requireField(this);" ></td>
									<td><?php echo e($ano); ?></td>
									<td><input type="text" <?php echo array_key_exists($ano, $yearsCatalogs_version) ? 'name="catalog[]" checked value="'. $yearsCatalogs_version[$ano] .'"' : ' '; ?> onkeyup="insertValue(this);" ></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			</div>

			<div class="row">
	            <div class="col-md-12">
	            	<div id="colores">
						<?php if($action == 'edit'): ?>	
							<?php foreach($colores as $color): ?>
								<?php echo $__env->make('admin.vehiculo_versiones.color', ['color' => $color], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
							<?php endforeach; ?>
						<?php endif; ?>
					</div>
					<br>
					<br>
					<div class="col-md-2 pull-right">
						<button id="agregar_colores" class="btn btn-primary pull-right">Agregar Colores</button>
					</div>
	            </div>
	        </div>
			
			<div class="form-group">
				<input type="submit" class="btn btn-primary" value="Guardar" />
				<a href="/admin/catalogo" class="btn btn-default">Cancelar</a>
			</div>

		</form>

	</div>
</div>

<div id="color" class="hide">
	<?php echo $__env->make('admin.vehiculo_versiones.color', ['color'=>new App\Models\VehiculoVersionesColores()], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
</div>

<?php $__env->startSection('scripts'); ?>
	<script type="text/javascript">

		function insertValue(input){
			let newValue = $(input).val();
			$(input).attr('value', newValue);
		}

		function requireField(element){
			if ( $(element).prop('checked') ) {
				$(element).parent('td').siblings('td').children('input').prop('required', 'required');
				$(element).parent('td').siblings('td').children('input').attr('name', 'catalog[]');
				$(element).parent('td').siblings('td').children('input').css('color', 'inherit');
			}else {
				$(element).parent('td').siblings('td').children('input').removeAttr('required');
				$(element).parent('td').siblings('td').children('input').css('color', 'transparent');
			}
		}

		$('#catalog_year').children('tr').each(function(index, el) {
			if( $(this).children('td:first-child').children('input').prop('checked') ){
				$(this).children('td:nth-child(3)').children('input').prop('required', 'required');
			}else {
				$(this).children('td:nth-child(3)').children('input').removeAttr('required');
			}
		});

		$('#form-vehiculo-version').bootstrapValidator({
			fields: {
				'modelo': {
	                validators: {
	                    notEmpty: {
	                        message: 'Por favor, seleccione un modelo.'
	                    }
	                }
	            },
	            'nombre': {
	                validators: {
	                    notEmpty: {
	                        message: 'Por favor, introduzca un nombre de versión.'
	                    },
	                    remote: {
		                	url: '/admin/versiones/validate-version-name',
		                	data: function(validator) {
		                        return {
		                            modelo: validator.getFieldElements('modelo').val(),
		                            id_version: validator.getFieldElements('id').val(),
		                        };
		                    },
		                }
	                }
	            },
	            'ano_version[]': {
	                validators: {
	                    notEmpty: {
	                        message: 'Por favor, seleccione al menos un año.'
	                    }
	                }
	            },
	            'nombre_bold[]': {
	                validators: {
	                    notEmpty: {
	                        message: 'Por favor, introduzca un nombre de color (negritas).'
	                    }
	                }
	            },
	            'nombre_regular[]': {
	                validators: {
	                    notEmpty: {
	                        message: 'Por favor, introduzca un nombre de color (regular).'
	                    }
	                }
	            },
	            'hexadecimal[]': {
	                validators: {
	                    notEmpty: {
	                        message: 'Por favor, introduzca el código en hexadecimal del color.'
	                    }
	                }
	            }
			},
		});

		$('#modelo').on('change', function (e) {
            $('#form-vehiculo-version').bootstrapValidator('revalidateField', 'nombre');
        });

		$('#agregar_colores').on('click', function(e){
			e.preventDefault();
			var $template = $("#color"),
                $clone    = $template
                                .clone()
                                .removeClass('hide')
                                .removeAttr('id')
                                .appendTo("#colores"),
                $option1   = $clone.find('[name="nombre_bold[]"]'),
                $option2   = $clone.find('[name="nombre_regular[]"]'),
                $option3   = $clone.find('[name="hexadecimal[]"]'),
                $option4   = $clone.find('[name="imagen[]"]');
            $('#form-vehiculo-version').bootstrapValidator('addField', $option1);
            $('#form-vehiculo-version').bootstrapValidator('addField', $option2);
            $('#form-vehiculo-version').bootstrapValidator('addField', $option3);
		});

		$('#colores').on('click', '.remove_color', function(e){
			$(this).closest('.bloque_color').remove();
			e.preventDefault();
		});

		function readURL(input,input2) {
		    if (input.files && input.files[0]) {
		        var reader = new FileReader();

		        reader.onload = function (e) {
		    		input2.siblings(".image_preview").attr('src', e.target.result);
		        }

		        reader.readAsDataURL(input.files[0]);
	    		input2.siblings(".image_preview").fadeIn(0);
		    }
		}

		$('#colores').on('change', '.color_image', function(e){
		    readURL(this,$(this));
		});
    </script>
<?php $__env->stopSection(); ?>