<?php

class Agro_View_Helper_MontaUnidades extends Zend_View_Helper_Abstract {

	public function montaUnidades($Proposta, $linha=false, $post=false, $pintaLinha=false, $conferencia=false) {
		$this->producaoGarantida = $Proposta->atributos('PROPRIEDADE', 'PROD_PRODUCAO_GARANTIDA');
		$this->produtividadeDeclarada = $Proposta->respostas('QUEST_PRODUTIVIDADE_DECLARADA');
		$this->atributos = $Proposta->atributos_rn('UNIDADE_SEGURADA');
		$respostas = $Proposta->unidades(false);
		$agrupamento = $Proposta->agrupamento();

		$this->conferencia = $conferencia;
		$wrongLines = false;

		if ($pintaLinha) {
			$wrongLines = $Proposta->unidadesSemCiclo();
		}

		if ($post) { $this->merge_array($respostas, $post); }

		if ($this->producaoGarantida) {
			$this->produtividadeEstimada = $Proposta->produtividade_estimada();
		}

		if (!$linha) {
			$this->montaCabecalhoUnidades($Proposta, $respostas);

			if ($respostas) {
				foreach ($respostas as $resposta) {
					$nro = $resposta['IS_ITEM'];
					$this->montaLinhaUnidades($Proposta, $nro, $wrongLines, $respostas);
				}
			}

			$this->montaRodapeUnidades();
		}

		$this->montaTextarea($Proposta, $respostas);
	}

	public function montaCabecalhoUnidades($Proposta, $respostas) {
		?>
		<script>
		<? if (is_array($respostas)): ?>
			var iUnidades = <?=count($respostas)?>;
		<? else: ?>
			var iUnidades = 0;
		<? endif; ?>

		$(document).ready(function() {
			var unidade = jQuery.format($("#template_unidades").val());

			/**
			 * Clique do botao inserir unidades seguradas
			 */
			$('#inserir_unidades').click(function () {
				if ($('#qtd_unidades').val()) {
					for (i=1; i<=$('#qtd_unidades').val(); i++) {
						$(unidade(iUnidades+i)).appendTo("#list_unidades");
					}

					$('#div_qtd_unidades').hide();
					$.bindDefaults();

					$('#div_qtd_unidades_cancel').show();
				}
			});

			/**
			 * Clique do botao inserir unidades seguradas
			 */
			$('#cancel_unidades').click(function () {
				if ($('#qtd_unidades').val()) {
					for (i=1; i<=($('#qtd_unidades').val()+iUnidades); i++) {
						$('#tr_unidade_'+(i+iUnidades)).remove();
					}
				}

				$('#div_qtd_unidades_cancel').hide();
				$('#div_qtd_unidades').show();
				$('#qtd_unidades').focus();
				$('#qtd_unidades').val('');
			});

			/**
			 * Clique do checkbox de seleção de todos os checks da lista
			 */
			$('#all').change(function () {
				if (!this.checked) {
					$('.formDefault').unCheckCheckboxes();
					$('#excluir_unidades').attr('disabled',true);
				} else {
					$('.formDefault').checkCheckboxes();
					$('#excluir_unidades').attr('disabled',false);
				}
			});

			/**
			 * Fica "escutando" quando a classe checkbox_unidade é clicada
			 */
			$('.checkbox_unidade').live('click', function(e) {
				check = false;

				var checked = $("input[class=checkbox_unidade]").filter(':checked').each (
					function() {
						check = true;
					}
				);

				if (!check) {
					$('#excluir_unidades').button('disable');
				} else {
					$('#excluir_unidades').button('enable');
				}
			});
		});
		</script>
		<div class="padding-10">
			<div class="row" id="div_qtd_unidades">
				<div class="field">
					<label>Digite o números de quadras/talhões que deseja inserir.</label>
					<input type="text" size="5" class="integer" id="qtd_unidades" /> <button type="button" id="inserir_unidades">Inserir</button>
				</div>
			</div>
			<div class="row hide" id="div_qtd_unidades_cancel">
				<div class="field">
					<button type="button" id="cancel_unidades">Cancelar</button>
				</div>
			</div>
		</div>

		<br style="clear:both;" />

		<div class="title-design"><div class="title"><span>Cadastro de Unidades Seguradas</span></div></div>
		<div style="width:100%;overflow-x:scroll">
			<table width="100%" class="grid_gray" cellpadding="0" cellspacing="1">
				<thead>
					<? if ($this->atributos): ?>
						<tr>
							<th nowrap="nowrap"><input type="checkbox" id="all" /></th>
							<th nowrap="nowrap" valign="top">Item</th>
							<? foreach ($this->atributos as $atributo):
								if (strtoupper($atributo['ds_chave_rn']) == 'IS_FRANQUIA_PARCIAL' or strtoupper($atributo['ds_chave_rn']) == 'IS_PREMIO_PARCIAL' or strtoupper($atributo['ds_chave_rn']) == 'IS_CICLO') {
									continue;
								}

								if ($this->producaoGarantida && strtoupper($atributo['ds_chave_rn']) == 'IS_PRODUCAO_GARANTIDA') {
									continue;
								}

								if ($this->produtividadeDeclarada == 2) {
									if (strtoupper($atributo['ds_chave_rn']) == 'IS_AREA' or strtoupper($atributo['ds_chave_rn']) == 'IS_PRODUTIVIDADE') {
										continue;
									}
								} else {
									if (strtoupper($atributo['ds_chave_rn']) == 'IS_PRODUCAO_PLANTA' or strtoupper($atributo['ds_chave_rn']) == 'IS_NRO_PLANTAS') {
										continue;
									}
								}
							?>
								<th nowrap="nowrap" valign="top"><?=$atributo['ds_descricao_atributo']?> <?=($atributo['fl_required'] ? '<br />*' : '')?></th>
							<? endforeach; ?>
						</tr>
					<? endif; ?>
				</thead>
				<tbody id="list_unidades">
					<?
	}

	public function montaLinhaUnidades($Proposta, $nro=false, $wrongLines=false, $respostas=array()) {
		$i = ($nro ? $nro : '{0}');

		$background = '';
		if (is_array($wrongLines) && in_array($nro, $wrongLines)) {
			$background = '#FFBBBC';
		}
		?>
		<tr id="tr_unidade_<?=$i?>">
			<td align="center" style="background:<?=$background?>">
				<input type="hidden" name="unidade[<?=$i?>][IS_ITEM]" value="<?=$i?>" />
				<input type="checkbox" id="ckeck_unidade_<?=$i?>" class="checkbox_unidade" value="<?=$i?>" />
			</td>
			<td align="center" style="background:<?=$background?>"><?=$i?></td>
			<? foreach ($this->atributos as $atributo):
				if (strtoupper($atributo['ds_chave_rn']) == 'IS_FRANQUIA_PARCIAL' or strtoupper($atributo['ds_chave_rn']) == 'IS_PREMIO_PARCIAL' or strtoupper($atributo['ds_chave_rn']) == 'IS_CICLO') {
					continue;
				}

				if ($this->producaoGarantida && strtoupper($atributo['ds_chave_rn']) == 'IS_PRODUCAO_GARANTIDA') {
					continue;
				}

				if ($this->produtividadeDeclarada == 2) {
					if (strtoupper($atributo['ds_chave_rn']) == 'IS_AREA' or strtoupper($atributo['ds_chave_rn']) == 'IS_PRODUTIVIDADE') {
						continue;
					}
				} else {
					if (strtoupper($atributo['ds_chave_rn']) == 'IS_PRODUCAO_PLANTA' or strtoupper($atributo['ds_chave_rn']) == 'IS_NRO_PLANTAS') {
						continue;
					}
				}
				?>
				<td align="center" style="background:<?=$background?>" nowrap="nowrap">
					<?=$this->getElement($atributo, $i, $Proposta->id_produto, $respostas);?>
				</td>
			<? endforeach; ?>
		</tr>
		<?
	}

	public function montaRodapeUnidades() {
					?>
				</tbody>
			</table>
		</div>
		<table width="100%" style="clear:both">
			<tr>
				<td align="right" style="padding:5px;">
					<button type="button" name="excluir" id="excluir_unidades" value="Excluir Selecionados" disabled>Excluir Selecionados</button>
					<button type="submit" name="salvar" id="salvar_unidades" value="Salvar">Salvar</button>
				</td>
			</tr>
		</table>
		<?
	}

	public function montaTextarea($Proposta) {
		?>
		<textarea id="template_unidades" class="hide">
			<?=$this->montaLinhaUnidades($Proposta);?>
		</textarea>
		<?
	}

	public function getElement($atributo, $item=false, $produto, $respostas) {
		if ($this->produtividadeEstimada) {
			$respostas[$item]['IS_PRODUTIVIDADE'] = $this->produtividadeEstimada;
		}

		$Element = new Agro_Element();
		$Element->setType($atributo['ds_chave_tipo_atributo']);
		$Element->setValue($respostas[$item][$atributo['ds_chave_rn']]);
		$Element->setClass($atributo['ds_chave_tipo_atributo'] . ' element_required');

		if ($atributo['ds_chave_rn'] == 'IS_PRODUTIVIDADE' && $this->producaoGarantida && !$this->conferencia) {
			$Element->setAttrib('readonly', 'readonly');
		}

		if ($atributo['ds_chave_tipo_atributo'] == 'data') {
			$Element->setSize(11);
		}

		if ($item) {
			$Element->setName("unidade[$item][{$atributo['ds_chave_rn']}]");
		}

		switch ($atributo['ds_chave_tipo_atributo']) {
			case 'lookup':
				$Element->setOptions($this->getOptions($atributo, $produto));
				break;

			default:
				$Element->setOptions($atributo['ds_valores_opcoes']);
				break;
		}

		return $Element->get();
	}

	public function getOptions($atributo, $produto) {
		$Db = Agro_Db_Table_Abstract::getDefaultAdapter();

		$select = $Db->select()->distinct(true);
		$select->from("{$atributo['ds_schema']}.{$atributo['ds_table']}", array($atributo['ds_option_value'], $atributo['ds_option_text']));
		$select->order($atributo['ds_option_text']);


		if ($atributo['ds_option_filter']) {
			$session = new Zend_Session_Namespace($atributo['ds_option_filter']);
			$select->where("{$atributo['ds_option_filter']} = ?", $produto);
		}

		$Rs = $Db->fetchAll($select);

		if ($Rs) {
			$options = array();
			foreach ($Rs as $Row) {
				$options[$Row[$atributo['ds_option_value']]] = $Row[$atributo['ds_option_text']];
			}
		}

		return $options;
	}

	public function merge_array(&$respostas, $post) {
		if (is_array($post)) {
			foreach ($post as $i => $row) {
				if (is_array($row)) {
					foreach ($row as $index => $value) {
						if ($value != $respostas[$i][$index]) {
							$respostas[$i][$index] = $value;
						}
					}
				}
			}
		}
	}

}