<!-- BEGIN FORM-->
<%= form_for(@product, :html => {:class=>"form-horizontal"}) do |f| %>
	<div class="portlet-body form" id="products_form">
		<% if @product.errors.any? %>
			<div class="alert alert-danger">
				<strong>Tiene <%= pluralize(@product.errors.count, "error") %> no se puede guardar el producto</strong><br>
			</div>
		<% end %>
		<div class="form-body">
			<input type="text" class="hidden" value="<%= @product.id %>" id="idproduct">
			<h4 class="form-section">Información general</h4>
			<div class="row">
				<div class="col-md-7">
					<%= hidden_field_tag :gain_margin, @pos_config.gain_margin %>
					<%= hidden_field_tag :tax_percent, @pos_config.tax_percent %>
					<div class="form-group">
						<%= f.label :sku, {:class=>"col-md-3 control-label"} do %>SKU <span class="required">*</span>
						<% end %>
						<div class="col-md-9">
							<div class="input-icon">
								<i class="fa fa-tag"></i>
								<%= f.text_field :sku, {:class=>"form-control input-medium", :readonly => true } %>
							</div>
							<span class="help-block">El SKU se genera automaticamente en base a la linea y sublinea seleccionadas. </span>
						</div>
					</div>
					<div class="form-group">
						<%= f.label :barcode, {:class=>"col-md-3 control-label"} do %> Codigo de barras <span class="required">*</span>
						<% end %>
						<div class="col-md-9">
							<div class="input-icon">
								<i class="fa fa-barcode"></i>
								<%= f.text_field :barcode, {:class=>"form-control input-medium", :readonly => true } %>
							</div>
							<span class="help-block">Para indicar el codigo de barras, debe de escanearlo. </span>
						</div>
					</div>
					<div class="form-group">
						<%= f.label :name, "Producto", {:class=>"col-md-3 control-label"} do %>Nombre
							<span class="required">*</span>
						<% end %>
						<div class="col-md-9">
							<%= f.text_field :name, {:class=>"form-control"} %>
						</div>
					</div>
					<div class="form-group">
						<%= f.label :description, "Descripción", {:class=>"col-md-3 control-label"} %>
						<div class="col-md-9">
							<%= f.text_area :description, {:class=>"form-control"} %>
						</div>
					</div>
					<div class="form-group">
						<%= f.label :unit_id, "Unidad de medida", {:class=>"col-md-3 control-label"} do %>Unidad de medida <span class="required">*</span>
						<% end %>
						<div class="col-md-9">
							<%= f.collection_select :unit_id, Unit.vigentes, :id, :unit, {:prompt => "Seleccione"}, {:class => "form-control input-medium"}   %>
						</div>
					</div>
				</div>
				<div class="col-md-5">
					<div class="form-group">
						<%= f.label :img_product, "Imagen producto", {:class=>"col-md-5 control-label"} %>
						<div class="col-md-7">
							<div class="fileinput fileinput-new" data-provides="fileinput">
								<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
									<% if @product.img_product? %>
										<%= image_tag @product.img_product %>
									<% else %>
										<%= image_tag "no-image.png" %>
									<% end %>
								</div>
								<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"> </div>
								<div>
									<span class="btn default btn-file">
										<span class="fileinput-new"> Seleccione imagen </span>
										<span class="fileinput-exists"> Cambiar </span>
										<%= f.file_field :img_product, {:class=>"default"} %>
										<%= f.hidden_field :img_product_cache %>
									</span>
									<a href="javascript:;" class="btn red fileinput-exists" data-dismiss="fileinput"> Borrar </a>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<h4 class="form-section">Información del producto</h4>
			<div class="row">
				<div class="form-group ">
					<%= f.label :inventory, "¿Se maneja inventario de este producto?", {:class=>"col-md-3 control-label"} do %>¿Este producto tendrá inventario?
						<span class="required">*</span>
					<% end %>
					<div class="col-md-9">
						<%= f.check_box(:inventory,
							{
								class: "make-switch",
								data: {
									on_color: "success",
									off_color: "danger",
									on_text: "Si",
									off_text: "No"
								}
							}, "true","false"
						) %>
					</div>
				</div>

				<div class="form-group">
					<%
						@category = nil
						@subcategory = nil;
						@prompt = 'Seleccione'
						@disabled = true
						if @product.categories[0].present? && @product.categories[0].parent_id == 0
							@category = @product.categories[0]
							@prompt = ''
						elsif @product.categories[0].present?
							@category = Category.find(@product.categories[0].parent_id)
							@subcategory = @product.categories[0]
							@disabled = false
						end
					%>
					<%= label_tag :categorias, "Líneas de producto", {:class=>"col-md-3 control-label"} do %>Líneas de producto
						<span class="required">*</span>
					<% end %>
					<div class="col-md-4">
							<%= select_tag 'categorias',
								options_from_collection_for_select(Category.activos_padre, 'id', 'category',
									:selected => (@category.id unless @category.nil?)),
									{:include_blank => "Seleccione", :class => 'form-control'} %>
					</div>
				</div>
				<div class="form-group">
					<%= f.label :category_ids, "Sublinea del producto", {:class=>"col-md-3 control-label"}   %>
					<div class="col-md-4">
						<%= f.collection_select(:category_ids, @category.nil? ? {} : Category.where(:parent_id => @category.id), :id, :category , options ={:include_blank => @prompt, :selected => (@subcategory.id unless @subcategory.nil?) }, :class => "form-control", :disabled => @disabled) %>
						<%= f.hidden_field :category_ids, {:id => 'subcategory_hidden'}%>
					</div>
				</div>
				<div class="form-group">
					<%= f.label :include_purchase_tax, "¿Incluir IVA en compra?", {:class=>"col-md-3 control-label"} do %> ¿Incluir IVA en compra?
						<span class="required">*</span>
					<% end %>
					<div class="col-md-9">
						<%= f.check_box(:include_purchase_tax,
							{
								class: "make-switch",
								data: {
									on_color: "success",
									off_color: "danger",
									on_text: "Si",
									off_text: "No"
								}
							}, "1","0"
						) %>
					</div>
				</div>
				<div class="form-group">
					<%= f.label :include_sale_tax, "¿Incluir IVA en venta?", {:class=>"col-md-3 control-label"} do %> ¿Incluir IVA en venta?
						<span class="required">*</span>
					<% end %>
					<div class="col-md-9">
						<%= f.check_box(:include_sale_tax,
							{
								class: "make-switch",
								data: {
									on_color: "success",
									off_color: "danger",
									on_text: "Si",
									off_text: "No"
								}
							}, "1","0"
						) %>
					</div>
				</div>
				<div class="form-group">
					<%= f.label :is_in_dollars, "¿Se compra en dolares?", {:class=>"col-md-3 control-label"} do %> ¿Se compra en dolares?
						<span class="required">*</span>
					<% end %>
					<div class="col-md-9">
						<%= f.check_box(:is_in_dollars,
							{
								class: "make-switch",
								data: {
									on_color: "success",
									off_color: "danger",
									on_text: "Si",
									off_text: "No"
								}
							}, "true","false"
						) %>
					</div>
				</div>
				<div class="form-group inventory">
					<%= f.label :price_base_dollars, "Precio de compra neto", {:class=>"col-md-3 control-label"} %>
					<div class="col-md-3">

						<div class="input-group <%=(@product.persisted? && @product.is_in_dollars?) ? '' : 'hidden' %>" id="price_base_usd_div">
							<span class="input-group-addon"> $ </span>
							<%= f.text_field :price_base_dollars, {:class=>"form-control mask_decimal"} %>
							<span class="input-group-addon"> USD </span>
						</div>

						<div class="input-group <%=(@product.persisted? && !@product.is_in_dollars?) ? '' : 'hidden' %>" id="price_base_mxn_div">
							<span class="input-group-addon"> $ </span>
							<%= f.text_field :price_base, {:class=>"form-control mask_decimal"} %>
							<span class="input-group-addon"> MXN </span>
						</div>

					</div>
				</div>
				<div class="form-group inventory">
					<%= f.label :price_sale, "Precio de venta base", {:class=>"col-md-3 control-label"} do %> Precio de venta base
						<span class="required">*</span>
					<% end %>
					<div class="col-md-3">
						<div class="input-group">
							<span class="input-group-addon"> $ </span>
							<%= f.text_field :price_sale, {:class=>"form-control mask_decimal"} %>
							<span class="input-group-addon"> MXN </span>
						</div>
					</div>
					<div class="col-md-6">
						<span class="help-block">El precio de venta base será calculado de acuerdo al porcentaje de utilidad especificado, solo en en caso de especificar el precio de compra neto.</span>
					</div>
				</div>
				<div class="form-group">
					<%= f.label :presentation, "¿El producto tiene variantes?", {:class=>"col-md-3 control-label"} do %>¿El producto tiene variantes?
						<span class="required">*</span>
					<% end %>
					<div class="col-md-9">
						<%= f.check_box(:presentation,
							{
								class: "make-switch",
								data: {
									on_color: "success",
									off_color: "danger",
									on_text: "Si",
									off_text: "No"
								},
								readonly: @with_presentation
							}, "true","false"
						) %>
					</div>
				</div>
			</div>
			<h4 class="form-section presentaciones">Variantes</h4>
			<div class="row presentaciones">
				<% if @product.persisted? %>
				<div class="col-md-9 col-md-offset-3">
					<%= render 'products_children' %>
				</div>
				<% else %>
				<div class="col-md-9 col-md-offset-3">
					<div class="alert alert-warning hidden">
						Son <strong id="variantes"></strong> variantes del producto.
					</div>
				</div>
				<div class="form-group ">
					<%= f.label :size_list, "Tallas", {:class=>"col-md-3 control-label"} %>
					<div class="col-md-9">
						<%= f.collection_select(:size_list, @product.size_list, :to_s, :to_s, { :include_blank => false }, {:class=>"form-control input-medium", 'data-role'=>'tagsinput', :multiple => true} ) %>
						<span class="help-block">Ingrese las diferentes tallas, separandolas con coma (,). </span>
					</div>
				</div>
				<div class="form-group ">
					<%= f.label :color_list, "Colores", {:class=>"col-md-3 control-label"} %>
					<div class="col-md-9">
						<%= f.collection_select(:color_list, @product.color_list, :to_s, :to_s, { :include_blank => false }, {:class=>"form-control input-medium", 'data-role'=>'tagsinput', :multiple => true} ) %>
						<span class="help-block">Ingrese los diferentes colores, separandolos con coma (,). </span>
					</div>
				</div>
				<div class="form-group ">
					<%= f.label :style_list, "Estilos", {:class=>"col-md-3 control-label"} %>
					<div class="col-md-9">
						<%= f.collection_select(:style_list, @product.style_list, :to_s, :to_s, { :include_blank => false }, {:class=>"form-control input-medium", 'data-role'=>'tagsinput', :multiple => true} ) %>
						<span class="help-block">Ingrese los diferentes estilos, separandolos con coma (,). </span>
					</div>
				</div>
				<%= hidden_field_tag :variants %>
				<% end %>
			</div>
		</div>
		<div class="form-actions">
			<div class="row">
				<div class="col-md-offset-3 col-md-9">
					<%= f.submit 'Guardar', {:class=>"btn green"} %>
					<%= link_to 'Cancelar', products_path(:filter => @filter, :current_page => @current_page), {:class=>"btn default"} %>
				</div>
			</div>
		</div>
	</div>
<% end %>
<script type="text/javascript">
	var timeout = null;
	var regex = /[a,e,i,o,u]/gi;
	var skuEdit = "";

	$(document).on('page:change', function() {

		App.init();

		$('.fileinput').fileinput();

		<% if @product.barcode.blank? %>
			$('body').barcodeListener().on('barcode.valid', function(e, code) {
				if($('#product_barcode').length > 0) {
					$('#product_barcode').val(code);
					validateBarcode(code);
				}
			});
		<% end %>

		presentaciones();
		getVariants();
		showPriceBaseInput(<%= @product.is_in_dollars? %>);


		$(document).on("cut copy paste",'form#new_product .presentaciones input[type=text]',function(e) {
			// evitar que se pueda copiar y pegar en los inputs de los tags de variantes
			e.preventDefault();
		});
	});

	$('#product_size_list').on('change', function(event) { getVariants(); });
	$('#product_color_list').on('change', function(event) { getVariants(); });
	$('#product_style_list').on('change', function(event) { getVariants(); });

	function presentaciones(){
		if ($('#product_presentation').is(':checked')){
			$('.presentaciones').removeClass('hidden');
		}
		else{ $('.presentaciones').addClass('hidden'); }
	}

	$('#product_presentation').on('switchChange.bootstrapSwitch', function(event, state) {
		presentaciones();
	});

	function getVariants(){
		sizes = $('#product_size_list').tagsinput('items');
		colors = $('#product_color_list').tagsinput('items');
		styles = $('#product_style_list').tagsinput('items');

		variantes = (sizes.length > 0 ? sizes.length : 1)
			* (colors.length > 0 ? colors.length : 1 )
				* (styles.length > 0 ? styles.length : 1);
		$('#variants').html(variantes);
		$('.alert-warning').removeClass('hidden');
		$('#variantes').html(variantes);
	}

	$('#categorias').on('change', function() {
		$('#product_sku').val('');
		if($('#categorias').val()) {
			$.ajax({
				type: "get",
				url:  '/getcategories/' + $(this).val(),
				dataType: 'json',
				success: function(data) {
					$('#product_category_ids').empty();
					if(data.length > 0) {
						$('#product_category_ids').attr('disabled', false);
						$('#product_category_ids').append("<option selected value='0'>Seleccione</option>")
					} else {
						$('#product_category_ids').attr('disabled', true);
						$('#subcategory_hidden').val($('#categorias').val());
						$('#product_category_ids').append("<option selected value='" + $('#categorias').val() +"'></option>")
					}
					for(i in data){
						$('#product_category_ids').append("<option value='" + data[i].id +"'>" + data[i].category+ "</option>")
					}
					fillSKU();
				}
			});
		}
	});

	$('#product_category_ids').on('change', function() {
		$('#subcategory_hidden').val($(this).val());
		fillSKU();
	});

	$('#product_price_base').on('input', function() {
		getSalePrice($(this));
	});

	$('#product_is_in_dollars').on('switchChange.bootstrapSwitch', function(event, state) {
		showPriceBaseInput(state);
	});

	function getSalePrice(input){
		clearTimeout(timeout);
		timeout = setTimeout(function () {
			var gainMargin = parseFloat($('#gain_margin').val());
			var purchasePrice = parseFloat(input.val());
			var gain = (gainMargin / 100) * purchasePrice
			$('#product_price_sale').val( (purchasePrice + gain).toFixed(2) );
		}, 500);
	}


	function getProductId() {
		$('#categorias').attr('disabled', true);
		$.ajax({
			type: "get",
			url:  '/get_max_product_id',
			dataType: 'json',
			success: function(data) {
				$('#categorias').attr('disabled', false);
				var sku = $('#product_sku').val();
				if(sku.length && !$('#idproduct').val()) {
					$('#product_sku').val(sku + "-" + data);
				} else {
					$('#product_sku').val(sku + "-" + $('#idproduct').val());
				}
			},
		});
	}

	function fillSKU() {
		var sku = $('#product_sku').val();
		if(sku.length <= 3) {
			$('#product_sku').val($('#categorias option:selected').text().substring(0,3).toUpperCase());
			getProductId();
		}

		sku = $('#product_sku').val();
		if(sku.length >= 3 && $('#product_category_ids').val() != "0") {
			var subcategory = $('#product_category_ids option:selected').text();
			if(subcategory){
				$('#product_sku').val(sku.substring(0,3) + '-' + subcategory.replace(regex, '')
					.substring(0,3).toUpperCase());
				getProductId();
			}
		}
	}

	function validateBarcode(barcode) {
		$.ajax({
			type: "get",
			url:  '/validate_unique_barcode/' + barcode,
			dataType: 'script',
			success: function(data) {
			}
		});
	}

	function showPriceBaseInput(state) {
		//true es en dolares, false en pesos
		if (state) {
		$('#price_base_usd_div').removeClass('hidden');
		$('#price_base_mxn_div').addClass('hidden');
		$('#product_price_base').val('');
		 <% unless @product.persisted? %>
			$('#product_price_sale').val('');
		 <% end %>
		} else {
		$('#price_base_mxn_div').removeClass('hidden');
		$('#price_base_usd_div').addClass('hidden');
		$('#product_price_base_dollars').val('');
		}
	}
</script>

