source: sipes/0.3-modules/proyectos_operativos_mcti/proyectos_operativos_mcti.module @ 364e0b2

stableversion-3.0
Last change on this file since 364e0b2 was 364e0b2, checked in by lhernandez <lhernandez@…>, 8 años ago

se agregaron las nuevas funcionalidades

  • Propiedad mode establecida a 100755
File size: 134.6 KB
Línea 
1<?php
2  /**
3  * Sistema Integral de Planificación y Presupuesto (SIPP)
4  * @file proyectos_operativos_mcti.module
5  * Drupal part Module to Sistema Integral de Planificación y Presupuesto (SIPP)
6  * Copyright 2013 Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana (CENDITEL)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  * @author Cenditel Merida - Ing. Jose Puentes
23  * @date 2014-12-04 // (a&#241;o-mes-dia)
24  * @version 0.1 // (0.1)
25  *
26  */
27
28/*
29 * Implementation of hook_menu()
30 */
31function proyectos_operativos_mcti_menu()  {
32  $items = array();
33  $items['proyectos_operativos_mcti_proyecto_generales_agrega_talento_js_util'] = array(
34    'title' => 'JS utilities',
35    'page callback' => 'proyectos_operativos_mcti_proyecto_generales_agrega_talento_js_util',
36    'access arguments' => array('ver planificador'),
37    'type' => MENU_CALLBACK,
38  );
39  $items['proyectos_operativos_mcti_agrega_indicadores_js_util'] = array(
40    'title' => 'JS utilities',
41    'page callback' => 'proyectos_operativos_mcti_agrega_indicadores_js_util',
42    'access arguments' => array('ver planificador'),
43    'type' => MENU_CALLBACK,
44  );
45  $items['proyectos_operativos_mcti_proyecto_basico_form_responsables'] = array(
46    'title' => 'JS utilities',
47    'page callback' => 'proyectos_operativos_mcti_proyecto_basico_form_responsables_js_util',
48    'access arguments' => array('ver planificador'),
49    'type' => MENU_CALLBACK,
50  );
51  $items['proyectos_operativos_mcti_proyecto_basico_form_cargar_responsables'] = array(
52    'title' => 'JS utilities',
53    'page callback' => 'proyectos_operativos_mcti_proyecto_basico_form_cargar_responsables_js_util',
54    'access arguments' => array('ver planificador'),
55    'type' => MENU_CALLBACK,
56  );
57  return $items;
58}
59
60/**
61 * Implementation of hook_theme().
62 */
63function proyectos_operativos_mcti_theme() {
64  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos_mcti') . '/templates';
65  return array(
66    'proyectos_operativos_mcti_ficha_proyecto' => array(
67      'arguments' => array(
68        'proyecto' => array(),
69      ),
70      'template' => 'proyectos-operativos-mcti-ficha-proyecto',
71      'path' => $proyectos_operativos_path,
72    ),
73  );
74}
75
76/**
77 * Implementation of hook_nodeapi()
78 */
79function proyectos_operativos_mcti_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
80  switch ($op) {
81    case 'presave':
82      if ($node->type == 'proyectos_operativos') {
83        $zerofill = 5;
84        $num = db_result(db_query("SELECT id FROM {proyectos_operativos} WHERE nid = %d", $node->nid));
85        $codigo = str_pad($num, $zerofill, '0', STR_PAD_LEFT);
86        $node->field_proyecto_codigo = array(array('value' => $codigo));
87        $node->title = $codigo;
88      }
89    break;
90  }
91}
92
93/*
94 * Impletations of hook_form_alter()
95 */
96function proyectos_operativos_mcti_form_alter(&$form, $form_state, $form_id) {
97  if ($form_id=='views_exposed_form' &&  $form['#id'] == 'views-exposed-form-ente-planificador-hierarchical-default') {//exclude to filters
98    global $user;
99    $ente = usuario_tiene_ente($user->uid);
100    $ente_planificador = 0;
101    if ($ente && $ente->nid) {
102      $ente_planificador = ente_planificador_leer_ente_planificadores($ente->nid);
103    }
104    if ($ente_planificador->tipo > 1) {
105      $form['ambito']['#access'] = false;
106      $form['#info']['filter-ambito']['label'] = 0;
107      //sector
108      $form['sector']['#access'] = false;
109      $form['#info']['filter-sector']['label'] = 0;
110    }
111    if ($ente_planificador->tipo > 2) {
112      $form['sidp']['#access'] = false;
113      $form['#info']['filter-sidp']['label'] = 0;
114    }
115  }
116  $name_workflow = $form['#wf']->name;
117  if ($form_id == 'workflow_tab_form' && $name_workflow == 'nuevo Proyecto') {
118    drupal_add_js(drupal_get_path('module', 'proyectos_operativos_mcti') . '/js/proyectos_operativos_mcti_datos_basicos.js'); 
119  }
120  //mostrar Balance Estimado Nacional de Servicios Energéticos
121  if ($form_id == 'proyectos_operativos_admin_settings') {
122    // formulario datos basicos
123    $form['basicos']['proyectos_operativos_muestra_proyecto_descripcion'] = array(
124      '#type' => 'checkbox',
125      '#title' => t('Recolectar la descripcion del proyecto.'),
126      '#weight' => 0,
127      '#default_value' => variable_get('proyectos_operativos_muestra_proyecto_descripcion', TRUE),
128    );
129    $form['basicos']['comuna'] = array(
130      '#title' => t('Comunas'),
131      '#type' => 'fieldset',
132      '#prefix' => '<div id="fields_datos_basicos_de_las_comunas">',
133      '#siffix' => '</div>',
134    );
135    $form['basicos']['comuna']['proyectos_operativos_muestra_codig_comuna'] = array(
136      '#type' => 'checkbox',
137      '#title' => t('Recolectar el codigo de la comuna.'),
138      '#default_value' => variable_get('proyectos_operativos_muestra_codig_comuna', TRUE),
139    );
140    $form['basicos']['comuna']['proyectos_operativos_muestra_ubicacin_comuna'] = array(
141      '#type' => 'checkbox',
142      '#title' => t('Recolectar la ubicacion de la comuna.'),
143      '#default_value' => variable_get('proyectos_operativos_muestra_ubicacin_comuna', TRUE),
144    );
145    $form['basicos']['comuna']['proyectos_operativos_muestra_name_comuna'] = array(
146      '#type' => 'checkbox',
147      '#title' => t('Recolectar el nombre de la comuna.'),
148      '#default_value' => variable_get('proyectos_operativos_muestra_name_comuna', TRUE),
149    );
150    $form['basicos']['responsables']['proyectos_operativos_muestra_responsables'] = array(
151      '#type' => 'checkbox',
152      '#title' => t('Recolectar los responsables del proyeto.'),
153      '#default_value' => variable_get('proyectos_operativos_muestra_responsables', TRUE),
154    );
155    $form['basicos']['proyectos_operativos_muestra_causas_abordadas'] = array(
156      '#type' => 'checkbox',
157      '#title' => t('Recolectar las causas abordadas.'),
158      '#weight' => 0,
159      '#default_value' => variable_get('proyectos_operativos_muestra_causas_abordadas', TRUE),
160    );
161    $form['basicos']['proyectos_operativos_muestra_problemas_abordados'] = array(
162      '#type' => 'checkbox',
163      '#title' => t('Recolectar los problemas abordados.'),
164      '#weight' => 0,
165      '#default_value' => variable_get('proyectos_operativos_muestra_problemas_abordados', TRUE),
166          );
167    // formulario datos generales
168    $form['generales']['proyectos_operativos_muestra_impacto_ambiental'] = array(
169      '#type' => 'checkbox',
170      '#title' => t('Recolectar el Impacto Ambiental del Proyecto.'),
171      '#default_value' => variable_get('proyectos_operativos_muestra_impacto_ambiental', TRUE),
172    );
173    $form['generales']['proyectos_operativos_muestra_servicios_balance'] = array(
174      '#type' => 'checkbox',
175      '#title' => t('Recolectar Balance Estimado Nacional de Servicios Energéticos.'),
176      '#default_value' => variable_get('proyectos_operativos_muestra_servicios_balance', TRUE),
177    );
178    $form['generales']['proyectos_operativos_muestra_programacion_anual'] = array(
179      '#type' => 'checkbox',
180      '#title' => t('Recolectar Programacion Anual por Consumidor.'),
181      '#default_value' => variable_get('proyectos_operativos_muestra_programacion_anual', TRUE),
182    );
183  }
184
185  if ($form_id == "proyectos_operativos_proyecto_genera_campos_form") {
186    $node_type = content_types('proyectos_operativos');
187    $fields = $node_type['fields'];
188    //programacion anual
189    if (variable_get('proyectos_operativos_muestra_impacto_ambiental', TRUE)) {
190      $arreglo['impacto'] = array(
191        'field_tipo_factores' => 'field_tipo_factores',
192        'field_factor_impact_multifc' => 'field_factor_impact_multifc',
193        'field_factor_segun_origen' => 'field_factor_segun_origen',
194        'field_factor_impact_multiog' => 'field_factor_impact_multiog',
195        'field_factor_naturaleza' => 'field_factor_naturaleza',
196        'field_factor_intensidad' => 'field_factor_intensidad',
197        'field_factor_extension' => 'field_factor_extension',
198        'field_factor_momento' => 'field_factor_momento',
199        'field_factor_persistencia' => 'field_factor_persistencia',
200        'field_factor_reversibilidad' => 'field_factor_reversibilidad',
201        'field_factor_sinergismo' => 'field_factor_sinergismo',
202        'field_factor_acumulacion' => 'field_factor_acumulacion',
203        'field_factor_relacion' =>'field_factor_relacion',
204        'field_factor_recuperabilidad' => 'field_factor_recuperabilidad',
205        'field_factor_importancia' => 'field_factor_importancia',
206        'field_factor_medids_impact' => 'field_factor_medids_impact',
207      );
208    }
209    if (variable_get('proyectos_operativos_muestra_servicios_balance', TRUE)) {
210      $arreglo['servicios']= array(
211       'field_balnc_progrmn_anu' => 'field_balnc_progrmn_anu',
212        'field_balance_fuente' => 'field_balance_fuente',
213        'field_balanc_tipofuent' => 'field_balanc_tipofuent',
214        'field_balanc_tipoprod' => 'field_balanc_tipoprod',
215        'field_balanc_unidmed' => 'field_balanc_unidmed',
216        'field_balanc_capacid' => 'field_balanc_capacid',
217        'field_balanc_anho' => 'field_balanc_anho',
218      );
219    }
220    if (variable_get('proyectos_operativos_muestra_responsables', TRUE)) {
221      $arreglo['responsables']['gerente'] = array(
222        'field_proyecto_nombre_gere' => 'field_proyecto_nombre_gere',
223        'field_proyecto_cedul_gere' => 'field_proyecto_cedul_gere',
224        'field_proyecto_corre_gere' => 'field_proyecto_corre_gere',
225        'field_proyecto_telef_gere' => 'field_proyecto_telef_gere',
226      );
227      $arreglo['responsables']['tecnico'] = array(
228        'field_proyecto_nom_r_tec' => 'field_proyecto_nom_r_tec',
229        'field_proyecto_ced_r_tec' => 'field_proyecto_ced_r_tec',
230        'field_proyecto_cor_r_tec' => 'field_proyecto_cor_r_tec',
231        'field_proyecto_tel_r_tec' => 'field_proyecto_cor_r_tec',
232        'field_proyecto_und_r_tec' => 'field_proyecto_und_r_tec',
233      );
234      $arreglo['responsables']['registrador'] = array(
235        'field_proyecto_nom_r_reg' => 'field_proyecto_nom_r_reg',
236        'field_proyecto_ced_r_reg' => 'field_proyecto_ced_r_reg',
237        'field_proyecto_cor_r_reg' => 'field_proyecto_cor_r_reg',
238        'field_proyecto_tel_r_reg' => 'field_proyecto_tel_r_reg',
239      );
240      $arreglo['responsables']['administrativo'] = array(
241        'field_proyecto_nom_r_adm' => 'field_proyecto_nom_r_adm',
242        'field_proyecto_ced_r_adm' => 'field_proyecto_ced_r_adm',
243        'field_proyecto_cor_r_adm' => 'field_proyecto_cor_r_adm',
244        'field_proyecto_tel_r_adm' => 'field_proyecto_tel_r_adm',
245        'field_proyecto_und_r_adm' => 'field_proyecto_und_r_adm',
246      );
247    }
248    if (!isset($_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid]) || !count($_SESSION['proyectos_operativos_mostrar_campos'][$form['#node']->nid])) {
249      if (count($fields)) {
250        foreach ($fields as $id => $field) {
251          if (!$field['display_settings']['full']['exclude']) {
252            //programacion anual
253            if (array_key_exists($id, $arreglo['servicios'])) {
254              $arreglo['fields_servicios'][$id] = $field['widget']['label'];
255            }
256            if (array_key_exists($id, $arreglo['impacto'])) {
257              $arreglo['fields_impacto'][$id] = $field['widget']['label'];
258            }
259            if (array_key_exists($id, $arreglo['responsables']['gerente'])) {
260              $arreglo['fields_gerente'][$id] = $field['widget']['label'];
261            }           
262            if (array_key_exists($id, $arreglo['responsables']['tecnico'])) {
263              $arreglo['fields_tecnico'][$id] = $field['widget']['label'];
264            }
265            if (array_key_exists($id, $arreglo['responsables']['registrador'])) {
266              $arreglo['fields_registrador'][$id] = $field['widget']['label'];
267            }
268            if (array_key_exists($id, $arreglo['responsables']['administrativo'])) {
269              $arreglo['fields_administrativo'][$id] = $field['widget']['label'];
270            }
271          }
272          elseif (array_key_exists($id,  $arreglo['servicios'])) {  //programacion anual
273           unset($arreglo['fields_servicios'][$id]);
274          }
275          elseif (array_key_exists($id,  $arreglo['impacto']['factor'])) {  //programacion anual
276            unset($arreglo['fields_impacto'][$id]);
277          }
278          elseif (array_key_exists($id, $arreglo['responsables']['gerente'])) {  //gerente
279            unset($arreglo['fields_gerente'][$id]);
280          }
281          elseif (array_key_exists($id,  $arreglo['responsables']['tecnico'])) {  //tecnico
282            unset($arreglo['fields_tecnico'][$id]);
283          }
284          elseif (array_key_exists($id, $arreglo['responsables']['registrador'])) {  //registrador
285            unset($arreglo['fields_registrador'][$id]);
286          }
287          elseif (array_key_exists($id, $arreglo['responsables']['administrativo'])) {  //administrativo
288            unset($arreglo['fields_administrativo'][$id]);
289          }
290        }
291      }
292    }
293    if(count($arreglo['fields_gerente'])) {
294      $form['db']['gerenteg'] = array(
295        '#type' => 'checkboxes',
296        '#options' => $arreglo['fields_gerente'],
297        '#default_value' => array(),
298        '#title' => t('Datos del Gerente'),
299        '#multiple' => TRUE,
300      );
301      $title_combos['gerenteg']['title'] = t('Datos del Gerente.');
302    }
303    if(count($arreglo['fields_tecnico'])) {
304      $form['db']['gerentet'] = array(
305        '#type' => 'checkboxes',
306        '#options' => $arreglo['fields_tecnico'],
307        '#default_value' => array(),
308        '#title' => t('Responsable Tecnico'),
309        '#multiple' => TRUE,
310      );
311      $title_combos['gerentet']['title'] = t('Responsable Tecnico.');
312    }
313    if (count($arreglo['fields_registrador'])) {
314      $form['db']['gerenter'] = array(
315        '#type' => 'checkboxes',
316        '#options' => $arreglo['fields_registrador'],
317        '#default_value' => array(),
318        '#title' => t('Responsable Registrador'),
319        '#multiple' => TRUE,
320      );
321      $title_combos['gerenter']['title'] = t('Responsable Registrador.');
322    }
323    if (count($arreglo['fields_administrativo'])) {
324      $form['db']['gerentea'] = array(
325        '#type' => 'checkboxes',
326        '#options' => $arreglo['fields_administrativo'],
327        '#default_value' => array(),
328        '#title' => t('Responsable administrativo'),
329        '#multiple' => TRUE,
330      );
331      $title_combos['gerentea']['title'] = t('Responsable Administativo.');
332    }
333    if (count($arreglo['fields_servicios'])) { ////Balance Estimado Nacional de Servicios Energéticos
334      $form['ip']['servicios'] = array(
335        '#type' => 'checkboxes',
336        '#options' => $arreglo['fields_servicios'],
337        '#default_value' => array(),
338        '#title' => t('Balance Estimado Nacional de Servicios Energéticos'),
339        '#multiple' => TRUE,
340      );
341      $title_combos['servicios']['title'] = t('Balance Estimado Nacional de Servicios Energéticos');
342     }
343     if (count($arreglo['fields_impacto'])) { //Impacto Ambiental del Proyecto
344      $form['ip']['impacto'] = array(
345        '#type' => 'checkboxes',
346        '#options' => $arreglo['fields_impacto'],
347        '#default_value' => array(),
348        '#title' => t('Impacto Ambiental del Proyecto'),
349        '#multiple' => TRUE,
350      );
351      $title_combos['impacto']['title'] = t('Impacto Ambiental del Proyecto');
352    }
353    $form['#title_combos'] += $title_combos;
354    //$form['#submit'][] = 'proyectos_operativos_proyecto_genera_campos_form_submit';
355  }
356
357   // formulario indicadores del proyecto
358  if ($form_id == "proyectos_operativos_proyecto_indicadores_form") {
359    $proyecto_leido = $form['#node'];
360    $node_type = content_types('proyectos_operativos');
361    $fields = $node_type['fields'];
362    //$form['#proyecto_fields'] = $fields;
363    $field_form = array();
364    $fields_form = array();
365    $fields_extra_form = array();
366    //Programacion anual por consumidor
367    $programacion = variable_get('proyectos_operativos_muestra_programacion_anual', TRUE);
368    $current_year = date("Y");
369    $years[0] = t('Seleccione');
370    for ($i = $current_year - 10; $i <= $current_year; $i++) {
371       $years[$i] = $i;
372    }
373    if ($programacion) {
374      $arreglo['programacion'] = array(
375        'field_progrmcn_anual_prog' => 'field_progrmcn_anual_prog',
376        'field_progrmcn_anual_unid' => 'field_progrmcn_anual_unid',
377        'field_progrmcn_anual_cap' => 'field_progrmcn_anual_cap',
378        'field_progrmcn_anual_anho' => 'field_progrmcn_anual_anho',
379      );
380      $form['programacion'] = array(
381        '#type' => 'fieldset',
382        '#title' => t('Programacion Anual por Consumidor'),
383        '#weight' => -1,
384      );
385      $prefixC = '';
386      $fields_extra_form1 = array();
387      foreach ($arreglo['programacion'] as $field_id => $field) {
388        $form['#proyectos_operativos_fields'][] = $field_id;
389        $prefixC .= '<th>' . $fields[$field_id]['widget']['label'] . '</th>';
390      }
391      $fields_extra_form['programacion'] = $fields_extra_form1;
392      $tamano_array = array();
393      foreach ($arreglo['programacion'] as $field_id => $field) { 
394        $tamano_array[] = count($proyecto_leido->{$field_id});
395      }
396      $cantidad = max($tamano_array);
397      $prefix = '';
398      $aux = '';
399      $aui = '';
400      for ($i = 0; $i < $cantidad; $i++) {
401        if ($i == 0) {
402          $prefix = '<div id="programacion-anual-modificar"><table><tr>' . $prefixC . '</tr><tr><td>';
403        }
404        else {
405          $prefix .= '<tr><td>';
406        }
407        foreach ($arreglo['programacion'] as $field_id => $field) {
408          if ($field == 'field_progrmcn_anual_anho') {
409            $valor = isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : '';
410            $form['programacion'][$field . '_' . $i] = array(
411              '#type' => 'select',
412              '#default_value' => $valor,
413              '#size' => $fields[$field_id]['size'],
414              '#maxlength' => $fields[$field_id]['max_length'],
415              '#required' => $fields[$field_id]['required'],
416              '#options' => $years,
417              '#prefix' => $prefix,
418              '#suffix' => '</td>',
419            );
420          }
421          elseif ($field == 'field_progrmcn_anual_cap') {
422            $valor = isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : '';
423            $form['programacion'][$field . '_' . $i] = array(
424              '#type' => 'textfield',
425              '#default_value' => $valor,
426              '#size' => $fields[$field_id]['size'],
427              '#maxlength' => $fields[$field_id]['max_length'],     
428              '#prefix' => $prefix,
429              '#suffix' => '</td>',
430            );
431          }
432          else {
433            $options = optionwidgets_options($fields[$field_id], FALSE);
434            $valor = isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : 0;
435            $form['programacion'][$field . '_' . $i] = array(
436              '#type' => 'select',   
437              '#default_value' => $valor,
438              '#options' => $options,         
439              '#prefix' => $prefix,
440              '#suffix' => '</td>',
441            );
442          }
443          $aux = $field_id;
444          $aui = $i;
445          $prefix = '<td>';
446        }
447        $form['programacion'][$aux . '_' . $aui]['#suffix'] .= '</tr>';
448      }
449      $form['programacion'][$aux . '_' . $aui]['#suffix'] .= '</table>';
450      $form['programacion']['cantidad_programacion'] = array('#type' => 'hidden', '#value' => $cantidad, '#suffix' => '</div>');
451      $form['programacion']['agrega_' . 'programacion'] = array(
452        '#type' => 'submit',
453        '#value' => t('Agregar otro campo'),
454        '#weight' => 100,
455        '#ahah' => array(
456          'path' => 'proyectos_operativos_mcti_agrega_indicadores_js_util/programacion',
457          'wrapper' => 'programacion-anual-modificar',
458          'method' => 'replace',
459          'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
460        ),
461      );
462    }
463    //Balance Estimado Nacional de Servicios Energéticos
464    if (variable_get('proyectos_operativos_muestra_servicios_balance', TRUE)) {
465      $arreglo['servicios'] = array(
466        'field_balnc_progrmn_anu' => 'field_balnc_progrmn_anu',
467        'field_balance_fuente' => 'field_balance_fuente',
468        'field_balanc_tipofuent' => 'field_balanc_tipofuent',
469        'field_balanc_tipoprod' => 'field_balanc_tipoprod',
470        'field_balanc_unidmed' => 'field_balanc_unidmed',
471        'field_balanc_capacid' => 'field_balanc_capacid',
472        'field_balanc_anho' => 'field_balanc_anho',
473     );
474     $form['balance'] = array(
475       '#type' => 'fieldset',
476       '#title' => t('Balance Estimado Nacional de Servicios Energéticos'),
477       '#weight' => -1,
478     );
479     $prefixC = '';
480     $fields_extra_form1 = array();
481     foreach ($arreglo['servicios'] as $field_id => $field) {
482       $form['#proyectos_operativos_fields'][] = $field_id;
483       $prefixC .= '<th>' . $fields[$field_id]['widget']['label'] . '</th>';
484     }
485     $fields_extra_form['balance'] = $fields_extra_form1;
486     $tamano_array = array();
487     foreach ($arreglo['servicios'] as $field_id => $field) { 
488       $tamano_array[] = count($proyecto_leido->{$field_id});
489     }
490     $cantidad = max($tamano_array);
491     $prefix = '';
492     $aux = '';
493     $aui = '';
494     for ($i = 0; $i < $cantidad; $i++) {
495       if ($i == 0) {
496         $prefix = '<div id="balance-servicios-modificar"><table><tr>' . $prefixC . '</tr><tr><td>';
497       }
498       else {
499         $prefix .= '<tr><td>';
500       }
501       foreach ($arreglo['servicios'] as $field_id => $field) {
502             if ($field == 'field_balanc_anho') {
503           $valor = isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : '';
504           $form['balance'][$field . '_' . $i] = array(
505             '#type' => 'select',
506             '#default_value' => $valor,
507             '#maxlength' => $fields[$field_id]['max_length'],
508             '#required' => $fields[$field_id]['required'],
509             '#options' => $years,
510             '#prefix' => $prefix,
511             '#suffix' => '</td>',
512           );
513         }
514         elseif ($field == 'field_balanc_capacid') {
515           $valor = isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : '';
516           $form['balance'][$field . '_' . $i] = array(
517             '#type' => 'textfield',
518             '#default_value' => $valor,
519             '#size' => $fields[$field_id]['size'],
520             '#maxlength' => $fields[$field_id]['max_length'],     
521             '#prefix' => $prefix,
522             '#suffix' => '</td>',
523           );
524         }
525         else {
526           $options = optionwidgets_options($fields[$field_id], FALSE);
527           $valor = isset($proyecto_leido->{$field_id}[$i]) ? $proyecto_leido->{$field_id}[$i]['value'] : 0;
528           $form['balance'][$field . '_' . $i] = array(
529             '#type' => 'select',   
530             '#default_value' => $valor,
531             '#options' => $options,         
532             '#prefix' => $prefix,
533             '#suffix' => '</td>',
534           );
535         }
536         $aux = $field_id;
537         $aui = $i;
538         $prefix = '<td>';
539       }
540       $form['balance'][$aux . '_' . $aui]['#suffix'] .= '</tr>';
541     }
542     $form['balance'][$aux . '_' . $aui]['#suffix'] .= '</table>';
543     $form['balance']['cantidad_balance'] = array('#type' => 'hidden', '#value' => $cantidad, '#suffix' => '</div>');
544     $form['balance']['agrega_' . 'balance'] = array(
545       '#type' => 'submit',
546       '#value' => t('Agregar otro campo'),
547       '#weight' => 100,
548       '#ahah' => array(
549         'path' => 'proyectos_operativos_mcti_agrega_indicadores_js_util/balance',
550         'wrapper' => 'balance-servicios-modificar',
551         'method' => 'replace',
552         'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
553        ),
554      );
555    }
556
557    //impacto ambiental del proyecto
558    $arreglo['factor']  = array();
559    if (variable_get('proyectos_operativos_muestra_impacto_ambiental', TRUE)) {
560      $field_form = array();
561      $fields_form = array();
562      $arreglo['factor'] = array(
563        'field_tipo_factores' => 'field_tipo_factores',
564        'field_factor_impact_multifc' => 'field_factor_impact_multifc',
565        'field_factor_segun_origen' => 'field_factor_segun_origen',
566        'field_factor_impact_multiog' => 'field_factor_impact_multiog',
567        'field_factor_naturaleza' => 'field_factor_naturaleza',
568        'field_factor_intensidad' => 'field_factor_intensidad',
569        'field_factor_extension' => 'field_factor_extension',
570        'field_factor_momento' => 'field_factor_momento',
571        'field_factor_persistencia' => 'field_factor_persistencia',
572        'field_factor_reversibilidad' => 'field_factor_reversibilidad',
573        'field_factor_sinergismo' => 'field_factor_sinergismo',
574        'field_factor_acumulacion' => 'field_factor_acumulacion',
575        'field_factor_relacion' =>'field_factor_relacion',
576        'field_factor_recuperabilidad' => 'field_factor_recuperabilidad',
577        'field_factor_importancia' => 'field_factor_importancia',
578        'field_factor_medids_impact' => 'field_factor_medids_impact',
579      );
580      $fields_form_factor = array();
581      if (is_array($fields) && count($fields)) {
582        foreach ($fields as $field_id => $field) {
583          if (array_key_exists($field_id, $arreglo['factor'])) {
584            $field_form[] = $field_id;
585            $fields_form[] = $field_id;
586            $form['#proyectos_operativos_fields'][] = $field_id;
587          }
588          elseif (variable_get('proyectos_operativos_muestra_factor_' . $field_id, FALSE)) {
589            $field_form[] = $field_id;
590            $fields_form[] = $field_id;
591            $form['#proyectos_operativos_fields'][] = $field_id;
592          }
593        }
594      }
595      if (is_array($field_form) && count($field_form)) {
596        module_load_include('inc', 'content', 'includes/content.node_form');
597        foreach ($field_form as $field_id) {
598          $field = content_fields($field_id, 'proyectos_operativos');
599          $form['#field_info'][$field_id] = $field;
600          $form += (array) content_field_form($form, $form_state, $field);
601        }
602      }
603    }
604    $submit = array();
605    foreach ($form['#submit'] as $name) {
606      if ($name == 'proyectos_operativos_proyecto_indicadores_form_submit') {
607        $submit[] = 'proyectos_operativos_mcti_agrega_indicadores_form_submit';
608      }
609      $submit[] = $name;
610    }
611    $form['#submit'] = $submit;
612  }
613
614  //formulario datos basicos de los proyectos operativos
615  if ($form_id == "proyectos_operativos_proyecto_basico_form") {
616    global $user;
617    drupal_add_js(drupal_get_path('module', 'proyectos_operativos_mcti') . '/js/proyectos_operativos_mcti_datos_basicos.js');
618    $node_type = content_types('proyectos_operativos');
619    $fields = $node_type['fields'];
620    $field_form = array();
621    $fields_form = array();
622    $fields_extra_form = array();
623    $fields_extra_form1 = array();
624    $form['field_proyecto_codigo']['#access'] = false;
625
626    //responsables de los proyectos
627    if (variable_get('proyectos_operativos_muestra_responsables', TRUE)) {
628      $arreglo = array();
629      $fields_extra_form1 = array();
630      $form['responsables'] = array(
631        '#title' => t(''),
632        '#type' => 'fieldset',
633        '#prefix' => '<div id="wrapper-proyectos-resposab">',
634        '#suffix' => '</div>',
635      );
636      $ente_agregar = $form['#parameters'][3];
637      $ente_planificador = node_load(1298);
638      if ($proyecto && $proyecto->nid && $proyecto->field_proyecto_ente[0]['nid']) {
639        $ente_planificador = ente_planificador_leer_ente_planificadores($proyecto->field_proyecto_ente[0]['nid']);
640      }
641      else {
642        $ente = usuario_tiene_ente($user->uid);
643        if ($ente && $ente->nid) {
644          $ente_planificador = ente_planificador_leer_ente_planificadores($ente->nid);
645        }
646        elseif($ente_agregar && user_access('admin planificador')) {
647          $ente_planificador = ente_planificador_leer_ente_planificadores($ente_agregar);
648        }
649      }
650      $options[$ente_planificador->nid] = $ente_planificador->title;
651      $form['responsables']['field_proyecto_entes'] = array(
652        '#title' => t('Insitución'),
653        '#type' => 'select',
654        '#options' => $options,
655        '#default_value' => $options,
656        '#prefix' => '<div id="field_proyecto_ente_datos_basicos">',
657        '#suffix' => '</div>',
658      );
659      $arreglo = array();
660      $tipos = array(
661        'gerente' => 'gerente',
662        'tecnico' => 'tecnico',
663        'registrador' => 'registrador',
664        'administrativo' => 'administrativo',
665      );
666      $arreglo['gerente'] = array(
667        0 => 'field_proyecto_nombre_gere',
668        1 => 'field_proyecto_cedul_gere',
669        2 => 'field_proyecto_corre_gere',
670        3 => 'field_proyecto_telef_gere',
671      );
672      $arreglo['tecnico'] = array(
673        0 => 'field_proyecto_nom_r_tec',
674        1 => 'field_proyecto_ced_r_tec',
675        2 => 'field_proyecto_cor_r_tec',
676        3 => 'field_proyecto_tel_r_tec',
677        4 => 'field_proyecto_und_r_tec',
678      );
679      $arreglo['registrador'] = array(
680        0 => 'field_proyecto_nom_r_reg',
681        1 => 'field_proyecto_ced_r_reg',
682        2 => 'field_proyecto_cor_r_reg',
683        3 => 'field_proyecto_tel_r_reg',
684      );
685      $arreglo['administrativo'] = array(
686        0 => 'field_proyecto_nom_r_adm',
687        1 => 'field_proyecto_ced_r_adm',
688        2 => 'field_proyecto_cor_r_adm',
689        3 => 'field_proyecto_tel_r_adm',
690        4 => 'field_proyecto_und_r_adm',
691      );
692      $fields_form_administrativo = array();
693
694      $query["gerente"] = db_query("SELECT DISTINCT(pp.field_proyecto_cedul_gere_value) as field_cedula, pp.field_proyecto_nombre_gere_value as field_nombre, pp.field_proyecto_corre_gere_email as field_email, pp.field_proyecto_telef_gere_value as field_tele FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.status=1 AND pp.vid=n.vid ORDER BY pp.field_proyecto_cedul_gere_value DESC", $ente_planificador->nid);
695
696      $query["tecnico"] = db_query("SELECT DISTINCT(pp.field_proyecto_ced_r_tec_value) as field_cedula, pp.field_proyecto_nom_r_tec_value as field_nombre, pp.field_proyecto_cor_r_tec_email as field_email, pp.field_proyecto_tel_r_tec_value as field_tele, pp.field_proyecto_und_r_tec_value as field_unidad  FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.status=1 AND pp.vid=n.vid ORDER BY pp.field_proyecto_ced_r_tec_value DESC", $ente_planificador->nid);
697
698      $query["registrador"] = db_query("SELECT DISTINCT(pp.field_proyecto_ced_r_reg_value) as field_cedula, pp.field_proyecto_nom_r_reg_value as field_nombre, pp.field_proyecto_cor_r_reg_email as field_email, pp.field_proyecto_tel_r_reg_value as field_tele FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.status=1 AND pp.vid=n.vid ORDER BY pp.field_proyecto_nom_r_reg_value DESC", $ente_planificador->nid);
699
700      $query["administrativo"] = db_query("SELECT DISTINCT(pp.field_proyecto_ced_r_adm_value) as field_cedula, field_proyecto_nom_r_adm_value as field_nombre, pp.field_proyecto_cor_r_adm_email as field_email, pp.field_proyecto_tel_r_adm_value as field_tele, pp.field_proyecto_und_r_adm_value as field_unidad FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.status=1 AND pp.vid=n.vid ORDER BY pp.field_proyecto_ced_r_adm_value DESC", $ente_planificador->nid);
701     
702      $field_form = array();
703      $fields_form = array();
704      $fields_extra_form1 = array();
705      $fields_extra_form1[] = 'field_proyecto_ente';
706
707      foreach ($tipos as $tips => $tip) {
708        $tam = '';
709        $prefixC = '';
710        $count = 0;
711        $rows = array();
712        $options = array();
713        $options[0] = t('Seleccione');
714        while ($row = db_fetch_object($query[$tip])) {
715          $options[$row->field_cedula] = $row->field_nombre .'('. $row->field_cedula .')';
716          $rows[$row->field_cedula] = array(
717            'name' => $row->field_nombre,
718            'cedula' => $row->field_cedula,
719            'email' => $row->field_email,
720            'phone' => $row->field_tele,
721            'unidad' => $row->field_unidad,
722          );
723        }
724        $resposables['responsables'][$tip] = $rows;
725        drupal_add_js($resposables, 'setting');
726
727        $options[] = t('Nuevo');
728        $form['responsables']['default_'.$tip] = array(
729          '#type' => 'select',
730          '#title' => t('Cargar datos del '.$tip),
731          '#default_value' => isset($form['#node']->field_proyecto_ced_r_adm['und'][0]['value']) ? $form['#node']->field_proyecto_ced_r_adm['und'][0]['value'] : 0,
732          '#options' => $options,
733          '#prefix' => '<fieldset id="wrapper-'.$tip.'-datos"><legend>' . t('Responsable '.$tip ) . '</legend>',
734        );
735        if (count($fields)) {
736          foreach ($arreglo[$tip] as $field_id => $field) {
737            $prefixC .= '<th>' . $fields[$field]['widget']['label'] . '</th>';
738          }
739          foreach ($arreglo[$tip] as $field_id => $field) {
740            foreach ($form['#node']->{$field} as $id => $campo) {
741              if ($form['#node']->{$field}[$id]['value']) {
742                  $default = $form['#node']->{$field}[$id]['value'];   
743                }
744                elseif ($form['#node']->{$field}[$id]['email']) {
745                  $default = $form['#node']->{$field}[$id]['email'];
746                }
747                else {
748                  $default = $form_state['values'][$field];
749                }
750              }
751              $prefix = '';
752              if ($count == 0) {
753                $prefix = '<div id="default_'.$tip.'"><table><tr>' . $prefixC . '</tr><tr><td>';
754              }
755              else {
756                $prefix .= '<td>';
757              }
758              $form['responsables'][$field] = array(
759                '#type' => 'textfield',
760                '#required' => $fields[$field]['required'],
761                '#maxlength' => $fields[$field]['max_length'],
762                '#size' => $fields[$field]['size'],
763                '#weight' => $fields[$field]['weight'],
764                '#description' => $fields[$field]['description'],
765                '#default_value' => $default,
766                '#prefix' => $prefix,
767                '#suffix' => '</td>',
768                '#attributes' => array('class' => $tip),
769              );
770              if($field == 'field_proyecto_cedul_gere' || $field == 'field_proyecto_ced_r_tec' || $field == 'field_proyecto_ced_r_reg' || $field == 'field_proyecto_ced_r_adm') {
771                $form['responsables'][$field]['#attributes']['placeholder'] = t( 'VXXXXXXXX' );
772              }
773              if($field == 'field_proyecto_telef_gere' || $field == 'field_proyecto_tel_r_tec' || $field == 'field_proyecto_tel_r_reg' || $field == 'field_proyecto_tel_r_adm') {
774                $form['responsables'][$field]['#attributes']['placeholder'] = t( 'xxxx-xxxx-xxx' );
775              }
776              $aux = $field;
777              $count++;
778            }
779          $form['responsables'][$aux]['#suffix'] .= '</tr>';
780          $form['responsables'][$aux]['#suffix'] .= '</table></div></fieldset>';
781        }
782      } //fin del foreach
783     
784      $form['responsables'][$aux]['#suffix'] .= '</div>';
785
786      foreach ($tipos as $tips => $tip) {
787        if (is_array($fields) && count($fields)) {
788          foreach ($fields as $field_id => $field) {
789            foreach ($arreglo[$tip] as $clave => $campo) {
790             if ($campo == $field_id) {
791                $form['#proyectos_operativos_fields'][] = $field_id;
792                $field_form[] = $field_id;
793                $fields_form[] = $field_id;
794              }
795              elseif (variable_get('proyectos_operativos_muestra_gerente_' . $field_id, FALSE)) {
796                $form['#proyectos_operativos_fields'][] = $field_id;
797                $field_form[] = $field_id;
798                $fields_form[] = $field_id;
799              }
800            }
801          }
802        }
803      }
804      $form['#validate'][] = 'proyectos_operativos_mcti_proyecto_basico_form_responsables_validate';
805      foreach ($form['#submit'] as $id => $name) {
806        if ($name == 'proyectos_operativos_proyecto_basico_form_submit') {
807          $submits[] = 'proyectos_operativos_mcti_proyecto_basico_form_responsables_submit';
808        }
809        $submits[] = $name;
810      }
811      $form['#submit'] = $submits;
812    }//end responsables
813
814    //datos de la comuna
815    $field_form = array();
816    $fields_form = array();
817    $fields_extra_form1 = array();
818    $arreglo = array();
819    $codig_comuna = variable_get('proyectos_operativos_muestra_codig_comuna', TRUE);
820    if ($codig_comuna) {
821      $form['#proyectos_operativos_fields_extra'][] = 'field_proyecto_codigo_comu';
822      $arreglo['field_proyecto_codigo_comu'] = 'field_proyecto_codigo_comu';
823    }
824    $ubicacin_comuna = variable_get('proyectos_operativos_muestra_ubicacin_comuna', TRUE);
825    if ($ubicacin_comuna) {
826      $form['#proyectos_operativos_fields_extra'][] = 'field_proyecto_ubicaci_comu';
827      $arreglo['field_proyecto_ubicaci_comu'] = 'field_proyecto_ubicaci_comu';
828    }
829    $nombre_comuna = variable_get('proyectos_operativos_muestra_name_comuna', TRUE);
830    if ($nombre_comuna) {
831      $form['#proyectos_operativos_fields_extra'][] = $fields_extra_form1;
832      $arreglo['field_proyecto_nombres_cum'] = 'field_proyecto_nombres_cum';
833    }
834    if ($codig_comuna || $ubicacin_comuna || $nombre_comuna) {
835      $fields_form_comuna = array();
836      if (is_array($fields) && count($fields)) {
837        foreach ($fields as $field_id => $field) {
838          if (array_key_exists($field_id, $arreglo)) {
839            $form['#proyectos_operativos_fields'][] = $field_id;
840            $field_form[] = $field_id;
841            $fields_form[] = $field_id;
842          }
843          elseif (variable_get('proyectos_operativos_muestra_comuna_' . $field_id, FALSE)) {
844            $form['#proyectos_operativos_fields'][] = $field_id;
845            $field_form[] = $field_id;
846            $fields_form[] = $field_id;
847          }
848        }
849      }
850    }
851    //localizacion internacional del proyecto
852    $arreglo = array();
853    $localizacion = variable_get('proyectos_operativos_muestra_ubicaci_interna', TRUE);
854    if ($localizacion) {
855      $arreglo['field_proyecto_ubicaci_inter'] = 'field_proyecto_ubicaci_inter';
856      if (is_array($fields) && count($fields)) {
857        foreach ($fields as $field_id => $field) {
858          if (array_key_exists($field_id, $arreglo)) {
859            $form['#proyectos_operativos_fields'][] = $field_id;
860            $field_form[] = $field_id;
861            $fields_form[] = $field_id;
862          }
863          elseif (variable_get('proyectos_operativos_muestra_ubicaci_inter_' . $field_id, FALSE)) {
864            $form['#proyectos_operativos_fields'][] = $field_id;
865            $field_form[] = $field_id;
866            $fields_form[] = $field_id;
867          }
868        }
869      }
870    }
871    $descripcion = variable_get('proyectos_operativos_muestra_proyecto_descripcion', TRUE);
872    if ($descripcion) {
873      $arreglo['field_descripcin_proyect'] = 'field_descripcin_proyect';
874      $form['#proyectos_operativos_fields_extra'][] = 'field_descripcin_proyect';
875    }
876    $causas = variable_get('proyectos_operativos_muestra_causas_abordadas', TRUE);
877    if ($causas) {
878      $arreglo['field_proyect_cau_abord'] = 'field_proyect_cau_abord';
879      $form['#proyectos_operativos_fields_extra'][] = 'field_proyect_cau_abord';
880    }
881    $problemas = variable_get('proyectos_operativos_muestra_problemas_abordados', TRUE);
882    if ($problemas) {
883      $arreglo['field_proyect_probl_abord'] = 'field_proyect_probl_abord';
884      $form['#proyectos_operativos_fields_extra'][] = 'field_proyect_probl_abord';
885    }
886    if ($descripcion || $causas || $problemas) {
887      $fields_form_basico = array();
888      if (is_array($fields) && count($fields)) {
889        foreach ($fields as $field_id => $field) {
890          if (array_key_exists($field_id, $arreglo)) {
891            $form['#proyectos_operativos_fields'][] = $field_id;
892            $field_form[] = $field_id;
893            $fields_form[] = $field_id;
894          }
895          elseif (variable_get('proyectos_operativos_muestra_otros_' . $field_id, FALSE)) {
896            $form['#proyectos_operativos_fields'][] = $field_id;
897            $field_form[] = $field_id;
898            $fields_form[] = $field_id;
899          }
900        }
901      }
902    }
903    //campos causas y problemas abordados con el proyecto
904    if (is_array($field_form) && count($field_form)) {
905      module_load_include('inc', 'content', 'includes/content.node_form');
906      foreach ($field_form as $field_id) {
907        $field = content_fields($field_id, 'proyectos_operativos');
908        $form['#field_info'][$field_id] = $field;
909        $form += (array) content_field_form($form, $form_state, $field);
910      }
911    }
912    //Monto Total del Proyecto para el año en curso.
913    $form['field_proyecto_monto_anual']['#pre_render'] = array('proyectos_operativos_mcti_field_proyecto_monto_anual_field_pre_render');
914    $form['field_proyecto_monto_anual'][0]['#required'] = 0;
915
916    foreach ($form['#validate'] as $id => $name) {
917      if ($name == 'proyectos_operativos_proyecto_basico_form_validate') {
918        $form['#validate'][$id] = 'proyectos_operativos_mcti_proyecto_basico_form_validate';
919      }
920    }
921  }//fin del datos basicos
922  if ($form_id == 'views_bulk_operations_form_asignar_proyectos_organismo_page_1') { //modificando el campo usuario a un campo del tipo select
923    $options = array();
924    global $user;
925    $ente_planificador = node_load($user->entes);
926          $options[0] = 'Seleccione';
927    $role1 = variable_get('ActorPlanificadorcoordinador1', 0);
928    if ($ente_planificador->tipo == 1 && $role1) {
929      $rol = $role1;
930    }
931    $role2 = variable_get('ActorPlanificadorevisor2', 0);
932    if ($ente_planificador->tipo == 2) {
933      $rol = $role2;
934    }
935    $role3 = variable_get('ActorPlanificadorevisor3', 0);
936    if ($ente_planificador->tipo == 3 && $role3) {
937      $rol = $role3;
938    }
939    $role4 = variable_get('ActorPlanificadorevisor4', 0);
940    if ($ente_planificador->tipo == 4 && $role4) {
941      $rol = $role4;
942    }
943    $title = 0;
944    $op_tt = '!=';
945    $var[0] = $rol;
946    $var[1] = $title;
947    //agregando el campo usuarios
948    if (isset($_GET['title']) && $_GET['title'] != 0) {
949      $op_tt = 'LIKE';
950      $var[1] = $_GET['title'];
951    }
952    $sql = "SELECT u.name, u.uid, u.nombres, u.apellidos, u.cedula FROM {users} as u INNER JOIN {ente_user_planificador} as e ON u.uid=e.usuario INNER JOIN {ente_planificador} as p ON p.nid=e.nid INNER JOIN {node} as n ON n.nid = p.nid INNER JOIN {users_roles} as r ON r.uid = u.uid WHERE r.rid = %d AND n.title " .$op_tt. " '%s'";
953    if (isset($_GET['ambito']) && $_GET['ambito'] != 0) {
954      $op_ab = '=';
955      $var[2] = $_GET['ambito'];
956      $sql .= " AND p.ambito " .$op_ab;
957    }
958    $var[3] = 0;
959    if (isset($_GET['sector']) && $_GET['sector'] != 0 ) {
960      $op_st = '=';
961      $var[3] = $_GET['sector'];
962      $sql .= " AND p.sector " .$op_st;
963    }
964    $query = db_query($sql, implode(',', $var));
965    while ($rows = db_fetch_object($query)) { //datos del usuario a mostrar
966      if ($rows->nombres || $rows->apellidos || $rows->cedula) {
967        $name = $rows->name . ', ' . $rows->nombres . ' ' . $rows->apellidos . '(' . $rows->cedula . ')';
968      }
969      else {
970        $name = $rows->name;
971      }
972      $options[$rows->uid] = $name;
973    }
974    $form['owner_name'] = array(
975      '#type' => 'select',
976      '#title' => t('Nombre de Usuario que ha de revisar el Proyecto'),
977      '#options' => $options,
978      '#description' => t('Nombre de usuario que se le ha de asignar el proyecto para su revisión.'),
979    );
980  }
981
982  if ($form_id == 'proyectos_operativos_proyecto_generales_form') {
983    //modificando el tipo de campo sector
984    $form['field_proyecto_sector']['tids']['#config']['level_labels']['status'] = 1;
985    $form['field_proyecto_sector']['tids']['#config']['level_labels']['labels'][1] = t('Sub-Sector');
986    //Empleos Generados
987    drupal_add_js(drupal_get_path('module', 'proyectos_operativos_mcti') . '/js/proyectos_operativos_mcti_generales.js');
988    $form['field_proyecto_efindirecto']['#title'] = t('Empleos Directos Sostenidos Femeninos');
989    $form['field_proyecto_emdirecto']['#title'] = t('Empleos Directos Nuevos Femeninos');
990    $form['field_proyecto_efdirecto']['#title'] = t('Empleos Directos Nuevos Masculinos');
991    $form['field_proyecto_emindirecto']['#title'] = t('Empleos Directos Sostenidos Masculinos');
992
993    //total empleos indirectos
994    $arregloI = array(
995      'field_proyecto_emindirecto' => 'field_proyecto_emindirecto',
996      'field_proyecto_efindirecto' => 'field_proyecto_efindirecto',
997    );
998    foreach ($arregloI as $id) {
999      $form[$id]['#pre_render'][] = 'proyectos_operativos_mcti_agregaclaseI_field_pre_render';
1000    }
1001    //total de empleos directos
1002    $arregloD = array(
1003      'field_proyecto_emdirecto' => 'field_proyecto_emdirecto',
1004      'field_proyecto_efdirecto' => 'field_proyecto_efdirecto',
1005    );
1006     foreach ($arregloD as $id) {
1007       $form[$id]['#pre_render'][] = 'proyectos_operativos_mcti_agregaclaseD_field_pre_render';
1008     }
1009     //total empleos directos femeninos
1010     $arregloDf = array(
1011       'field_proyecto_efindirecto' => 'field_proyecto_emindirecto',
1012       'field_proyecto_efdirecto' => 'field_proyecto_efdirecto',
1013     );
1014     foreach ($arregloDf as $id) {
1015       $form[$id]['#pre_render'][] = 'proyectos_operativos_mcti_agregaclaseDF_field_pre_render';
1016     }
1017     //total empleos directos masculinos
1018     $arregloDf = array(
1019       'field_proyecto_emindirecto' => 'field_proyecto_efindirecto',
1020       'field_proyecto_emdirecto' => 'field_proyecto_emdirecto',
1021     );
1022     foreach ($arregloDf as $id) {
1023       $form[$id]['#pre_render'][] = 'proyectos_operativos_mcti_agregaclaseDM_field_pre_render';
1024     }
1025     //cargando los valores por defecto.
1026     $sumas['empleos']['empleos_estimadosDf'] = 'empleos_estimadosDf';
1027     $sumas['empleos']['empleos_estimadosDm'] = 'empleos_estimadosDm';
1028     $sumas['empleos']['empleos_estimadosD'] = 'empleos_estimadosD';
1029     $sumas['empleos']['empleos_estimadosI'] = 'empleos_estimadosI';
1030     drupal_add_js($sumas, 'setting');
1031
1032     if (variable_get('proyectos_operativos_muestra_beneficiario', TRUE)) {
1033       $arreglo = array(
1034         'field_proyecto_beneficiario' => 'field_proyecto_beneficiario',
1035         'field_proyectos_masculino_d' => 'field_proyectos_masculino_d',
1036       );
1037       $labels = array(
1038         'field_proyecto_beneficiario' => 'Beneficiario ',
1039         'field_proyectos_masculino_d' => 'Número estimado de beneficiarios masculinos',
1040         'field_proyectos_femenino_i' => 'Número estimado de beneficiarios femeninos',
1041       );
1042       if (variable_get('proyectos_operativos_muestra_beneficiarios_indirectos', TRUE)) {
1043        $arreglo['field_proyectos_femenino_i'] = 'field_proyectos_femenino_i';
1044      }
1045      $prefixC = '';
1046      foreach ($arreglo as $field_id => $field) {
1047        $prefixC .= '<th>'.$labels[$field_id].'</th>';
1048      }
1049      $prefixC .= '<th>' . t('Total') . '</th>';
1050      $node_type = content_types('proyectos_operativos');
1051      $fields = $node_type['fields'];
1052      $tamano_array = array();
1053      foreach ($arreglo as $field_id => $field) {
1054        $tamano_array[] = count($form['#node']->{$field_id});
1055      }
1056      $cantidad_beneficiario = max($tamano_array);
1057      for ($i = 0; $i < $cantidad_beneficiario; $i++) {
1058        $prefix = '';
1059        if ($i == 0) {
1060          $prefix = '<span title="Este campo es obligatorio." class="form-required" style="margin-left: 75px; margin-top: -30px; position: absolute;">*</span><div id="beneficiario-modificar"><table align="center"><tr>' . $prefixC . '</tr><tr><td>';
1061        }
1062        else {
1063          $prefix .= '<tr><td>';
1064        }
1065        foreach ($arreglo as $field_id => $field) {
1066          $form['beneficiario'][$field_id . '_' . $i]['#prefix'] = $prefix;
1067          if ($field_id != 'field_proyecto_beneficiario') {
1068            if (!isset($total_arreglo[$field_id])) {
1069              $total_arreglo[$field_id] = 0;
1070            }
1071            $subtotal += (int) $valor;
1072            $totales += (int) $valor;
1073            $total_arreglo[$field_id] += (int) $valor;
1074           }
1075           $aux = $field_id;
1076           $aui = $i;
1077           $prefix = '<td align="center">';
1078         }
1079        //total masculino y femenino
1080       
1081        //excluir los siguientes campos.
1082        $form['beneficiario']['field_proyectos_masculino_i'. '_' . $i]['#access'] = false;
1083        $form['beneficiario']['field_proyectos_femenino_d'. '_' . $i]['#access'] = false;
1084        $form['beneficiario']['field_proyectos_masculino_i'. '_' . $i]['#value'] = 0;
1085        $form['beneficiario']['field_proyectos_femenino_d'. '_' . $i]['#value'] = 0;
1086       
1087        unset($form['beneficiario'][$aux . '_' . $aui]['#suffix']);
1088        $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiario_' . $i . '_total">' . $subtotal . '</div></td>';
1089        $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '</tr>';
1090      }
1091      $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<tr align="right"><td><b>' . t('TOTAL DE BENEFICIARIOS') . '</b></td>';
1092      foreach ($arreglo as $field_id => $field) {
1093        if ($field_id != 'field_proyecto_beneficiario') {
1094          $sumas['beneficiarios']['beneficiarios_' . $field_id] = 'beneficiarios_' . $field_id;
1095          $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiarios_' . $field_id . '_total">' . $total_arreglo[$field_id] . '</div></td>';
1096        }
1097      }
1098      $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="todosbeneficiarios_total">' . $totales . '</div></td></tr>';
1099      $form['beneficiario'][$aux . '_' . $aui]['#suffix'] .= '</table>';
1100      $form['beneficiario']['agrega_' . 'beneficiario']['#ahah'][ 'path'] = 'proyectos_operativos_mcti_proyecto_generales_agrega_talento_js_util/beneficiario';
1101      foreach ($form['#validate'] as $key => $name) {
1102        if ($name == 'proyectos_operativos_proyecto_generales_form_validate'){
1103          $form['#validate'][$key] = 'proyectos_operativos_mcti_proyecto_generales_form_validate';
1104        }
1105      }
1106    }
1107  }
1108}
1109
1110/**
1111 * Implementation of proyectos_operativos_proyecto_generales_form_validate().
1112 * Validar formulario de datos generales (proyectos operativos).
1113 */
1114function proyectos_operativos_mcti_proyecto_generales_form_validate($form, &$form_state) {
1115  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1116  if ($op == t('Cancelar')) {
1117    return;
1118  }
1119  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
1120  drupal_add_js($form['#format_number'], 'setting');
1121  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
1122  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_generales.js');
1123  drupal_add_js($form['#sumas'], 'setting');
1124  if (count($form['#proyectos_operativos_fields_extra'])) {
1125    foreach($form['#proyectos_operativos_fields_extra'] as $id => $arreglo) {
1126      $all_null = TRUE;
1127      unset($arreglo[2]);
1128      unset($arreglo[3]);
1129      $cantidad = $form_state['values']['cantidad_' . $id];
1130      for($i = 0; $i < $cantidad; $i++) {
1131        $null = TRUE;
1132        $first_campo = FALSE;
1133        foreach($arreglo as $campo) {
1134          if (!$first_campo) {
1135            $first_campo = $campo;
1136          }
1137          if ($form_state['values'][$campo . '_' . $i] && trim($form_state['values'][$campo . '_' . $i]) != '') {
1138            $all_null = FALSE;
1139            $null = FALSE;
1140          }
1141          if ($campo == 'field_proyecto_esfuerzo' || $campo == 'field_proyectos_masculino_d' || $campo == 'field_proyectos_masculino_i' || $campo == 'field_proyectos_femenino_d' || $campo == 'field_proyectos_femenino_i') {
1142            $start = $form_state['values'][$campo . '_' . $i];
1143            $value = (int) $start;
1144            if ($start != $value) {
1145              form_set_error($campo . '_' . $i, t('Solo números enteros son permitidos en el campo %field.' . $start, array('%field' => t($form['#proyecto_fields'][$campo]['widget']['label']))));
1146            }
1147            elseif ($value < 0) {
1148              form_set_error($campo . '_' . $i, t('Solo números enteros positivos son permitidos en el campo %field.' . $start, array('%field' => t($form['#proyecto_fields'][$campo]['widget']['label']))));
1149            }
1150          }
1151        }
1152        if (!$null) {
1153          foreach($arreglo as $campo) {
1154            $campos = $form['#proyecto_fields'][$campo]['widget']['label']= 0;
1155            if ($campo == 'field_proyectos_masculino_d') {
1156              $campos == 'Número estimado de beneficiarios masculinos';
1157            }
1158            if ($campo == 'field_proyectos_femenino_i') {
1159              $campos == 'Número estimado de beneficiarios femeninos';
1160            }
1161            if (trim($form_state['values'][$campo . '_' . $i]) == '') {
1162              form_set_error($campo . '_' . $i, t('El campo @campo_name no puede estar vacio', array('@campo_name' => $campos)));
1163            }
1164          }
1165        }
1166      }
1167      if ($all_null) {
1168        form_set_error($first_campo . '_0', t('Debe llenar al menos un campo'));
1169      }
1170    }
1171  }
1172}
1173
1174/**
1175 * Guarda los datos de los indicadores
1176 */
1177function proyectos_operativos_mcti_agrega_indicadores_form_submit($form, &$form_state) {
1178  //agregando el Balance Estimado Nacional de Servicios Energéticos 
1179  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1180  if ($op != t('Cancelar')) {
1181    $tipos = array('programacion', 'balance');
1182    $arreglo['balance'] = array(
1183      'field_balnc_progrmn_anu' => 'field_balnc_progrmn_anu',
1184      'field_balance_fuente' => 'field_balance_fuente',
1185      'field_balanc_tipofuent' => 'field_balanc_tipofuent',
1186      'field_balanc_tipoprod' => 'field_balanc_tipoprod',
1187      'field_balanc_unidmed' => 'field_balanc_unidmed',
1188      'field_balanc_capacid' => 'field_balanc_capacid',
1189      'field_balanc_anho' => 'field_balanc_anho',
1190    );
1191    $arreglo['programacion'] = array(
1192      'field_progrmcn_anual_prog' => 'field_progrmcn_anual_prog',
1193      'field_progrmcn_anual_unid' => 'field_progrmcn_anual_unid',
1194      'field_progrmcn_anual_cap' => 'field_progrmcn_anual_cap',
1195      'field_progrmcn_anual_anho' => 'field_progrmcn_anual_anho',
1196    );
1197    foreach ($tipos as $keys => $tipo) {
1198       $cantidad = $form_state['values']['cantidad_'.$tipo];
1199       for ($i = 0; $i < $cantidad; $i++) {
1200         foreach ($arreglo[$tipo] as $campo) {
1201           $form_state['values'][$campo][$i] = array('value' => trim($form_state['values'][$campo . '_' . $i]));
1202         }
1203       }
1204    }
1205  }
1206}
1207
1208/**
1209 * valida las entradas de los responsables del proyecto en el formulario de datos basicos
1210 */
1211function proyectos_operativos_mcti_proyecto_basico_form_responsables_validate($form, &$form_state) {
1212  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1213  if ($op == t('Cancelar')) {
1214    return;
1215  }
1216  if (trim($form_state['values']['field_proyecto_corre_gere']) && !valid_email_address(trim($form_state['values']['field_proyecto_corre_gere']))) {
1217    form_set_error('field_proyecto_corre_gere', t('"%mail" is not a valid email address',array('%mail' => $form_state['values']['field_proyecto_corre_gere'])));
1218  }
1219  if (trim($form_state['values']['field_proyecto_cor_r_tec']) && !valid_email_address(trim($form_state['values']['field_proyecto_cor_r_tec']))) {
1220    form_set_error('field_proyecto_cor_r_tec', t('"%mail" is not a valid email address',array('%mail' => $form_state['values']['field_proyecto_cor_r_tec'])));
1221  }
1222  if (trim($form_state['values']['field_proyecto_cor_r_reg']) && !valid_email_address(trim($form_state['values']['field_proyecto_cor_r_reg']))) {
1223    form_set_error('field_proyecto_cor_r_reg', t('"%mail" is not a valid email address',array('%mail' => $form_state['values']['field_proyecto_cor_r_reg'])));
1224  }
1225  if (trim($form_state['values']['field_proyecto_cor_r_adm']) && !valid_email_address(trim($form_state['values']['field_proyecto_cor_r_adm']))) {
1226    form_set_error('field_proyecto_cor_r_adm', t('"%mail" is not a valid email address',array('%mail' => $form_state['values']['field_proyecto_cor_r_adm'])));
1227  }
1228  //validacion de la cedula
1229  if (!preg_match("/^(V|E){1}([0-9]){8}$/",$form_state['values']['field_proyecto_cedul_gere'])) {
1230    form_set_error('field_proyecto_cedul_gere', t('La cédula de identidad %cedula debe tener el formato V00000000 sin puntos.',array('%cedula' => $form_state['values']['field_proyecto_cedul_gere'])));
1231  }
1232  if (!preg_match("/^(V|E){1}([0-9]){8}$/",$form_state['values']['field_proyecto_ced_r_tec'])) {
1233    form_set_error('field_proyecto_ced_r_tec', t('La cédula de identidad %cedula debe tener el formato V00000000 sin puntos.',array('%cedula' => $form_state['values']['field_proyecto_ced_r_tec'])));
1234  }
1235  if (!preg_match("/^(V|E){1}([0-9]){8}$/",$form_state['values']['field_proyecto_ced_r_reg'])) {
1236    form_set_error('field_proyecto_ced_r_reg', t('La cédula de identidad %cedula debe tener el formato V00000000 sin puntos.',array('%cedula' => $form_state['values']['field_proyecto_ced_r_reg'])));
1237  }
1238  if (!preg_match("/^(V|E){1}([0-9]){8}$/",$form_state['values']['field_proyecto_ced_r_adm'])) {
1239    form_set_error('field_proyecto_ced_r_adm', t('La cédula de identidad %cedula debe tener el formato V00000000 sin puntos.',array('%cedula' => $form_state['values']['field_proyecto_ced_r_adm'])));
1240  }
1241}
1242
1243/*
1244 * Implementation of proyectos_operativos_proyecto_basico_form_validate()
1245 * Validar formulario de datos basicos (proyectos operativos).
1246 */
1247function proyectos_operativos_mcti_proyecto_basico_form_validate($form, &$form_state) {
1248  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1249  if ($op == t('Cancelar')) {
1250    return;
1251  }
1252  $proyectos_operativos_path = drupal_get_path('module', 'proyectos_operativos');
1253  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos_extra.js');
1254  drupal_add_js($proyectos_operativos_path . '/js/proyectos_operativos2.js');
1255  //drupal_add_js($form['#format_number'], 'setting');
1256  $form_state['values']['field_proyecto_monto_anual'][0]['value'] = str_replace("", $form['#format_number']['format_number']['thousands_sep'], $form_state['values']['field_proyecto_monto_anual'][0]['value']);
1257  $form_state['values']['field_proyecto_monto_anual'][0]['value'] = str_replace(".", $form['#format_number']['format_number']['dec_point'], $form_state['values']['field_proyecto_monto_anual'][0]['value']);
1258  $form_state['values']['field_proyecto_total'][0]['value'] = str_replace("", $form['#format_number']['format_number']['thousands_sep'], $form_state['values']['field_proyecto_total'][0]['value']);
1259  $form_state['values']['field_proyecto_total'][0]['value'] = str_replace(".", $form['#format_number']['format_number']['dec_point'], $form_state['values']['field_proyecto_total'][0]['value']);
1260
1261  // garantizar el formato numerico y no exponencial con numeros grandes
1262  if ($form_state['values']['field_proyecto_monto_anual'][0]['value'] != 0)  {
1263    $form_state['values']['field_proyecto_monto_anual'][0]['value'] = number_format($form_state['values']['field_proyecto_monto_anual'][0]['value'], $form['#format_number']['format_number']['decimals'], '.', '');
1264  }
1265  $form_state['values']['field_proyecto_total'][0]['value'] = number_format($form_state['values']['field_proyecto_total'][0]['value'], $form['#format_number']['format_number']['decimals'], '.', '');
1266  if (trim($form_state['values']['field_proyecto_correo'][0]['email']) && !valid_email_address(trim($form_state['values']['field_proyecto_correo'][0]['email']))) {
1267    form_set_error('field_proyecto_correo', t('"%mail" is not a valid email address',array('%mail' => $form_state['values']['field_proyecto_correo'][0]['email'])));
1268  }
1269  if ($form_state['values']['field_proyecto_monto_anual'][0]['value'] < 0) {
1270    form_set_error('field_proyecto_monto_anual', t('El monto anual del proyecto no puede ser negativo'));
1271  }
1272  $start = $form_state['values']['field_proyecto_total'][0]['value'];
1273  $value = preg_replace('@[^-0-9]@', '', $start);
1274  if ($start != $value) {
1275    form_set_error('field_proyecto_total', t('Solo números enteros son permitidos en el monto anual del proyecto.'));
1276  }
1277  $start = $form_state['values']['field_proyecto_monto_anual'][0]['value'];
1278  $value = preg_replace('@[^-0-9]@', '', $start);
1279  if ($start != $value) {
1280    form_set_error('field_proyecto_monto_anual', t('Solo números enteros son permitidos en el monto total del proyecto'));
1281  }
1282  if ($form['#count_ae'] && $form['#montos_asignados'] > $value) {
1283    form_set_error('field_proyecto_monto_anual', t('El monto anual del proyecto (@monto_proyecto Bs.) es inferior al asignado a las Acciones Específicas (@monto_asignado Bs.)', array('@monto_proyecto' => number_format($value, $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']), '@monto_asignado' => number_format($form['#montos_asignados'], $form['#format_number']['format_number']['decimals'], $form['#format_number']['format_number']['dec_point'], $form['#format_number']['format_number']['thousands_sep']))));
1284  }
1285  if ($form_state['values']['field_proyecto_total'][0]['value'] < 0) {
1286    form_set_error('field_proyecto_total', t('El monto anual del proyecto no puede ser negativo'));
1287  }
1288  if ($form_state['values']['field_proyecto_monto_anual'][0]['value'] > $form_state['values']['field_proyecto_total'][0]['value']) {
1289    form_set_error('field_proyecto_monto_anual', t('El monto anual debe ser menor o igual al monto total del proyecto'));
1290  }
1291  //lamentablemente date no valida que from sea menor que to
1292  if ($form_state['values']['field_proyecto_fecha_i'][0]['value'] > $form_state['values']['field_proyecto_fecha_f'][0]['value']) {
1293    form_set_error('field_proyecto_fecha_i', t('La fecha de inicio debe ser menor a la fecha de culminación'));
1294  }
1295  //validamos el añofield_proyecto_plurianual
1296  $fecha = explode('-', $form_state['values']['field_proyecto_fecha_i'][0]['value']);
1297  if (is_array($fecha) && count($fecha)) {
1298    if ($form['#proyecto_anho'] != $fecha[0]) {
1299      form_set_error('field_proyecto_fecha_i',t('El año de inicio del proyecto debe ser igual a @year', array('@year' => $form['#proyecto_anho'])));
1300    }
1301  }
1302  if ($form['#count_ae'] && $form['#fechas_validacion']['inicio'] < $form_state['values']['field_proyecto_fecha_i'][0]['value']) {
1303    $fecha_dia = explode(' ', $fecha[2]);
1304    form_set_error('field_proyecto_fecha_i',t('La fecha de inicio del proyecto (@fecha_inicio) es mayor a la menor fecha de inicio de las Acciones Específicas (@fecha_aei)', array('@fecha_inicio' => $fecha_dia[0] . '-' . $fecha[1] . '-' . $fecha[0], '@fecha_aei' => $form['#fechas_validacion']['inicio_texto'])));
1305  }
1306  $fecha = explode('-', $form_state['values']['field_proyecto_fecha_f'][0]['value']);
1307  if (is_array($fecha) && count($fecha)) {
1308    if ($form['#proyecto_anho'] != $fecha[0]) {
1309      form_set_error('field_proyecto_fecha_f',t('El año de finalización del debe ser igual a @year', array('@year' => $form['#proyecto_anho'])));
1310    }
1311  }
1312  if ($form['#count_ae'] && $form['#fechas_validacion']['fin'] > $form_state['values']['field_proyecto_fecha_f'][0]['value']) {
1313    $fecha_dia = explode(' ', $fecha[2]);
1314    form_set_error('field_proyecto_fecha_f',t('La fecha de culminación del proyecto (@fecha_inicio) es menor a la menor fecha de inicio de las Acciones Específicas (@fecha_aei)', array('@fecha_inicio' => $fecha_dia[0] . '-' . $fecha[1] . '-' . $fecha[0], '@fecha_aei' => $form['#fechas_validacion']['fin_texto'])));
1315  }
1316}
1317
1318/**
1319 * Agrega los responsables del proyecto
1320 */
1321function proyectos_operativos_mcti_proyecto_basico_form_responsables_submit($form, &$form_state) {
1322  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
1323  if ($op != t('Cancelar')) {
1324    $tipos = array('gerente', 'tecnico', 'registrador', 'administrativo', 'ubicacion', 'otros_datos');
1325    $arreglo['gerente'] = array(
1326      0 => 'field_proyecto_nombre_gere',
1327      1 => 'field_proyecto_cedul_gere',
1328      2 => 'field_proyecto_corre_gere',
1329      3 => 'field_proyecto_telef_gere',
1330    );
1331    $arreglo['tecnico'] = array(
1332      0 => 'field_proyecto_nom_r_tec',
1333      1 => 'field_proyecto_ced_r_tec',
1334      2 => 'field_proyecto_cor_r_tec',
1335      3 => 'field_proyecto_tel_r_tec',
1336      4 => 'field_proyecto_und_r_tec',
1337    );
1338    $arreglo['registrador'] = array(
1339      0 => 'field_proyecto_nom_r_reg',
1340      1 => 'field_proyecto_ced_r_reg',
1341      2 => 'field_proyecto_cor_r_reg',
1342      3 => 'field_proyecto_tel_r_reg',
1343    );
1344    $arreglo['administrativo'] = array(
1345      0 => 'field_proyecto_nom_r_adm',
1346      1 => 'field_proyecto_ced_r_adm',
1347      2 => 'field_proyecto_cor_r_adm',
1348      3 => 'field_proyecto_tel_r_adm',
1349      4 => 'field_proyecto_und_r_adm',
1350    );
1351    foreach ($tipos as $keys => $tipo) {
1352      foreach ($arreglo[$tipo] as $campo) {
1353        if (isset($form_state['values'][$campo])) {
1354          if ($campo == 'field_proyecto_cor_r_adm' || $campo == 'field_proyecto_cor_r_tec' || $campo == 'field_proyecto_cor_r_reg' || $campo == 'field_proyecto_corre_gere') {
1355            $form_state['values'][$campo] = array(array('email' => $form_state['values'][$campo]));
1356          }
1357          else {
1358            $form_state['values'][$campo] = array(array('value' => $form_state['values'][$campo]));
1359          }
1360        }
1361      }
1362    }
1363  }
1364}
1365
1366/**
1367 * Agrega los instituciones responsables
1368 */
1369function proyectos_operativos_proyecto_ente_field_pre_render($element) {
1370  global $user;
1371  if ($ente) {
1372    if (count($element['nid']['nid']['#options'])) {
1373      foreach ($element['nid']['nid']['#options'] as $id => $entes){
1374        if ($ente->nid != $id) {
1375          unset($element['nid']['nid']['#options'][$id]);
1376        }
1377      }
1378    }
1379  }
1380  return $element;
1381}
1382/*
1383 * Total de empleos Directos
1384 */
1385function proyectos_operativos_mcti_agregaclaseD_field_pre_render($element) {
1386  $element[0]['value']['#attributes']['class'] .= ' empleos_estimadosD';
1387  $element[0]['value']['#attributes']['onchange'] .= ";sumaempleos('empleos_estimadosD');";
1388  return $element;
1389}
1390 
1391/**
1392 * Total empleos directos masculinos
1393 */
1394function proyectos_operativos_mcti_agregaclaseDF_field_pre_render($element) {
1395  $element[0]['value']['#attributes']['class'] .= ' empleos_estimadosDf';
1396  $element[0]['value']['#attributes']['onchange'] .= ";sumaempleos('empleos_estimadosDf');";
1397  return $element;
1398}
1399
1400/**
1401 * Total de empleos directos masculinos
1402 */
1403function proyectos_operativos_mcti_agregaclaseDM_field_pre_render($element) {
1404  $element[0]['value']['#attributes']['class'] .= ' empleos_estimadosDm';
1405  $element[0]['value']['#attributes']['onchange'] .= ";sumaempleos('empleos_estimadosDm');";
1406  return $element;
1407}
1408
1409/**
1410 * Total de empleos indirectos
1411 */
1412function proyectos_operativos_mcti_agregaclaseI_field_pre_render($element) {
1413  $element[0]['value']['#attributes']['class'] .= ' empleos_estimadosI';
1414  $element[0]['value']['#attributes']['onchange'] .= ";sumaempleos('empleos_estimadosI');";
1415  return $element;
1416}
1417
1418/**
1419 * Agrega una clase CSS y ahah a la estructura del campo nid para la institucion de datos basicos
1420 */
1421function proyectos_operativos_mcti_field_proyecto_monto_anual_field_pre_render($element) {
1422  $element[0]['value']['#attributes']['disabled'] = 'disabled';
1423  return $element;
1424}
1425
1426/**
1427 * Agrega ahah al campo
1428 */
1429function proyectos_operativos_mcti_field_proyecto_monto_total_field_pre_render($element) {
1430  $element['value']['NO']['#ahah'] = array(
1431    'event' => 'change',
1432    'path' => 'proyectos_operativos_mcti_proyecto_monto_anual_js/no',
1433    'wrapper' => 'field-proyecto-total-wrraper',
1434    'method' => 'replace',
1435    'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
1436  );
1437  $element['value']['SI']['#ahah'] = array(
1438    'event' => 'change',
1439    'path' => 'proyectos_operativos_mcti_proyecto_monto_anual_js/si',
1440    'wrapper' => 'field-proyecto-total-wrraper',
1441    'method' => 'replace',
1442    'progress' => array('type' => 'bar', 'message' => t('Please wait...')),
1443        );
1444  // this part may be naughty
1445  form_expand_ahah($element['value']['NO']);
1446  form_expand_ahah($element['value']['SI']);
1447  return $element;
1448}
1449
1450/**
1451 * Implementation of hook_action_info().
1452 * asignar los proyectos operativos a los usuarios.
1453 */
1454 function proyectos_operativos_mcti_action_info() {
1455   return array(
1456     'proyectos_operativos_mcti_action' => array(
1457       'description' => t('Asignar Proyectos para su revision a usuarios'),
1458       'type' => 'node',
1459       'configurable' => true,
1460     ),
1461   );
1462 }
1463
1464/**
1465 * Agrega los datos de la accion
1466 */
1467 function proyectos_operativos_mcti_action(&$node, $context) {
1468   $owner_name = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $context['owner_uid']));
1469   $ente_name = db_result(db_query("SELECT title FROM {node} WHERE nid = %d", $context['row']->nid, $context['owner_uid']));
1470   db_query("DELETE FROM {proyectos_operativos_asignados} WHERE nid_node = %d", $context['row']->nid);
1471   db_query("INSERT INTO {proyectos_operativos_asignados} (nid_node, uid_users) VALUES(%d, %d)", $context['row']->nid, $context['owner_uid']);
1472   drupal_set_message(t('Se asigno el Ente Planificador %ente al usuario %user' , array('%ente'=> $ente_name, '%user' => $owner_name)));
1473 }
1474
1475/**
1476 * Implementation of a configurable Drupal action.
1477 */
1478function proyectos_operativos_mcti_action_form($context) {
1479  module_load_include('inc', 'content', 'includes/content.node_form');
1480  $form = array();
1481  $form['#settings'] = $context['settings'];   
1482  $form_state = array();
1483  $weight = -100;
1484  $fields = array();
1485  // Get the content types of the selected nodes if any. Otherwise, get all types.
1486  if (!empty($context['selection']) && isset($context['view'])) {
1487    $fields = proyectos_operativos_mcti_action_fields();
1488  }
1489  foreach ($fields as $field) {
1490    // The field info and widget.
1491    $form += (array)$field['form'];
1492    if (is_array($form['#node']->{$field['field_name']})) {
1493      foreach ($form['#node']->{$field['field_name']} as $v_key => $v_item) {
1494        $form[$field['field_name']][$v_key]['#default_value'] = $v_item;
1495      }
1496    }
1497    else {
1498      $form[$field['field_name']]['#default_value'] = $form['#node']->{$field['field_name']};
1499    }
1500    if (empty($form[$field['field_name']])) continue;
1501  } //end foreach
1502  return $form;
1503}
1504
1505/**
1506 * Defincion de los campos que han de estar disponibles durante la implementacion del hook_action_info
1507 */
1508function proyectos_operativos_mcti_action_fields($type = NULL) {
1509  $fields = array();
1510  $fields['owner_name'] = array(
1511    'label' => t('user'),
1512    'form' => array(
1513      'owner_name' => array(
1514      '#type' => 'textfield',
1515      '#title' => t('Nombre de Usuario'),
1516      '#autocomplete_path' => 'user/autocomplete',
1517      '#size' => '30',
1518      '#maxlength' => '60',
1519      '#description' => t('Nombre de usuario al que desea asignar el proyecto'),
1520      ),
1521    ),
1522  );
1523  return $fields;
1524}
1525
1526/**
1527 * validando el nombre del usuario
1528 */
1529function proyectos_operativos_mcti_action_validate($form, $form_state) {
1530  $count = db_result(db_query("SELECT COUNT(uid) FROM {users} WHERE uid = '%s'", $form_state['values']['owner_name']));
1531  if (intval($count) != 1) {
1532    form_set_error('owner_name', t('Please enter a valid username.'));
1533  }
1534}
1535 
1536/**
1537 * implementacion del hook_action_submit()
1538 */
1539function proyectos_operativos_mcti_action_submit($form, $form_state) {
1540  // Username can change, so we need to store the ID, not the username.
1541  $uid = db_result(db_query("SELECT uid from {users} WHERE uid = '%s'", $form_state['values']['owner_name']));
1542  return array('owner_uid' => $uid);
1543}
1544
1545/*
1546 * Creando el permiso para revisar los proyectos
1547 */
1548function proyectos_operativos_mcti_perm() {
1549  return array('review proyectos operativos');
1550}
1551
1552/**
1553 * Implementation of hook_views_api().
1554 */
1555function proyectos_operativos_mcti_views_api() {
1556  return array(
1557    'api' => '2.0',
1558    'path' => drupal_get_path('module', 'proyectos_operativos_mcti') . '/includes/views',
1559  );
1560}
1561
1562/**
1563 * Implementation of hook_theme_registry_alter().
1564 */
1565function proyectos_operativos_mcti_theme_registry_alter(&$theme_registry) {
1566  if ($theme_registry['proyectos_operativos_proyecto_generales_form']) {   
1567    $theme_registry['proyectos_operativos_proyecto_generales_form']['function'] = 'theme_proyectos_operativos_mcti_proyecto_generales_form';
1568  }
1569  if ($theme_registry['proyectos_operativos_proyecto_indicadores_form']) {   
1570    $theme_registry['proyectos_operativos_proyecto_indicadores_form']['function'] = 'theme_proyectos_operativos_mcti_proyecto_indicadores_form';
1571  }
1572  if ($theme_registry['proyectos_operativos_proyecto_basico_form']) {   
1573    $theme_registry['proyectos_operativos_proyecto_basico_form']['function'] = 'theme_proyectos_operativos_mcti_proyecto_basico_form';
1574  }
1575}
1576
1577/**
1578 * Agrega los nuevos campos en el formulario proyecto en la pestanha generales
1579 */
1580function theme_proyectos_operativos_mcti_proyecto_generales_form($form) {
1581  $output = '';
1582  if ($form['#count_ae'] && $form['#montos_asignados'] != $form['#node']->field_proyecto_monto_anual[0]['value']) {
1583    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
1584    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
1585    $format_number = array(
1586      'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
1587      'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
1588      'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
1589    );
1590    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas con un monto total de @montos_asignados Bs, el cual difiere con el monto asignado en el proyecto para el @title_monto_total_proyecto_year (@monto_proyecto). Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@montos_asignados' => number_format($form['#montos_asignados'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '@title_monto_total_proyecto_year' => $form['#proyecto_fields']['field_proyecto_monto_anual']['widget']['label'], '@monto_proyecto' => number_format($form['#node']->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
1591    $output .= '<div id="mensaje-mostrar-monto" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
1592  }
1593  if ($form['#count_ae'] && $fechas_validacion['inicio'] && $fechas_validacion['fin'] && ($fechas_validacion['inicio_time'] < $fechas_validacion['inicio_current_time'] || $fechas_validacion['fin_current_time'] < $fechas_validacion['fin_time'])) {
1594    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
1595    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
1596    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas que difieren con la @title_fecha_de_inicio o @title_fecha_de_final del Proyecto. Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@title_fecha_de_inicio' => $form['#proyecto_fields']['field_proyecto_fecha_i']['widget']['label'], '@title_fecha_de_final' => $form['#proyecto_fields']['field_proyecto_fecha_f']['widget']['label'], '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
1597    $output .= '<div id="mensaje-mostrar-time" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
1598  }
1599  $output .= '<fieldset><legend>' . t('Clasificación Sectorial del Gasto ONAPRE') . '</legend>' . drupal_render($form['field_proyecto_sector']);
1600  if (count($form['#fields_form_dg_se'])) {
1601    foreach ($form['#fields_form_dg_se'] as $id_c) {
1602      $output .= drupal_render($form[$id_c]);
1603    }
1604  }
1605  $output .= '</fieldset>';
1606
1607  if (variable_get('proyectos_operativos_muestra_talento', TRUE)) {
1608    $output .= drupal_render($form['talento']);
1609  }
1610  if (variable_get('proyectos_operativos_muestra_capacidades', TRUE)) {
1611    $output .= drupal_render($form['capacidades']);
1612  }
1613  $output .= '<fieldset><legend>' . t('Instituciones') . '</legend>' . drupal_render($form['field_proyecto_relacion']);
1614  if (count($form['#fields_form_dg_r'])) {
1615    foreach($form['#fields_form_dg_r'] as $id_c) {
1616      $output .= drupal_render($form[$id_c]);
1617    }
1618  }
1619
1620  $output .= '</fieldset>';
1621  $output .= '<fieldset><legend>' . t('Empleos Generados') . '</legend>' . t('Nro Estimados de Empleos:');
1622  $output .= '<table>';
1623 
1624  $output1 = '<tr>';
1625  $arreglo = array(
1626    'field_proyecto_emindirecto' => 'field_proyecto_emindirecto',
1627    'field_proyecto_efindirecto' => 'field_proyecto_efindirecto',
1628  );
1629  foreach($arreglo as $empleo) {
1630    $output1 .= '<th>' . $form[$empleo]['#title'] . '</th>';
1631    $form[$empleo][0]['value']['#title'] = '';
1632    $output1 .= '<td>' . drupal_render($form[$empleo]) . '</td>';
1633  }
1634  $output1 .= '<th>' . t('Total empleos directos Nuevos') . '</th>';
1635  $output1 .= '<td><div class="empleos_estimadosI_totales"></div></td>';
1636  $output1 .= '</tr>';
1637   
1638  $output1 .= '<tr>';
1639  $arreglo = array(
1640    'field_proyecto_efdirecto' => 'field_proyecto_efdirecto',
1641    'field_proyecto_emdirecto' => 'field_proyecto_emdirecto',
1642  );
1643  foreach($arreglo as $empleo) {
1644    $output1 .= '<th>' . $form[$empleo]['#title'] . '</th>';
1645    $form[$empleo][0]['value']['#title'] = '';
1646    $output1 .= '<td>' . drupal_render($form[$empleo]) . '</td>';
1647  }
1648  $output1 .= '<th>' . t('Total empleos Directos Sostenidos') . '</th>';
1649  $output1 .= '<td colspan="3"><div class="empleos_estimadosD_totales"></div></td>';
1650  $output1 .= '</tr>';
1651
1652  $output1 .= '<tr>';
1653  $output1 .= '<th>' . t('Total de Empleos Masculinos') . '</th>';
1654  $output1 .= '<td><div class="empleos_estimadosDf_totalesDf"></div></td>';
1655  $output1 .= '<th>' . t('Total de Empleos Femeninos') . '</th>';
1656  $output1 .= '<td><div class="empleos_estimadosDm_totalesDm"></div></td>';
1657  $output1 .= '<th>' . t('Total de Empleos Directos') . '</th>';
1658  $output1 .= '<td><div class="empleos_generados_total"></div></td>';
1659  $output1 .= '</tr>';
1660 
1661  $output .= $output1 .'</table></fieldset>';
1662  if (variable_get('proyectos_operativos_muestra_beneficiario', TRUE)) {
1663    $output .= drupal_render($form['beneficiario']);
1664  }
1665  $output .= '<fieldset><legend>' . t('Objetivos del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_og']) . drupal_render($form['field_proyecto_oe']);
1666  if (count($form['#fields_form_dg_o'])) {
1667    foreach($form['#fields_form_dg_o'] as $id_c) {
1668      $output .= drupal_render($form[$id_c]);
1669    }
1670  }
1671  $output .= '</fieldset>';
1672
1673  $output .= drupal_render($form);
1674  return $output;
1675}
1676
1677/**
1678 * Agrega los nuevos campos en el formulario proyecto en la pestanha datos basicos
1679 */
1680function theme_proyectos_operativos_mcti_proyecto_basico_form($form) {
1681$output = '';
1682  $fecha_inicio = $form['#fechas_validacion']['inicio'];
1683  if ($form['#count_ae']) {
1684    $format_number = array(
1685      'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
1686      'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
1687      'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
1688    );
1689    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas, con un monto total de @montos_asignados Bs asignados. y fechas de Inicio  @inicio y fin  @fin. Tome en consideración estos valores al momento de modificar los valores de los campos @title_fecha_i, @final title_fecha_f y @title_monto_total_proyecto_year', array('@count_ae' => $form['#count_ae'], '@montos_asignados' => number_format($form['#montos_asignados'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '@inicio' => $form['#fechas_validacion']['inicio_texto'], '@fin' => $form['#fechas_validacion']['fin_texto'], '@title_fecha_i' => $form['field_proyecto_fecha_i']['#title'], '@final title_fecha_f' => $form['field_proyecto_fecha_f']['#title'], '@title_monto_total_proyecto_year' => $form['field_proyecto_monto_anual']['#title'] ));
1690    $output .= '<div id="mensaje-mostrar" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
1691  }
1692  $output .= '<fieldset><legend>' . t('Datos Básicos de Identificación del Proyecto');
1693  $output .= '</legend>' . drupal_render($form['field_proyecto_titulo']);
1694  if (isset($form['field_proyecto_codigo']) && $form['field_proyecto_codigo']['#access']) {
1695    $output .= drupal_render($form['field_proyecto_codigo']);
1696  } 
1697  $descripcion = variable_get('proyectos_operativos_muestra_proyecto_descripcion', TRUE);
1698  if ($descripcion) {
1699    $output .= drupal_render($form['field_descripcin_proyect']);
1700  }
1701  if (isset($form['field_proyecto_fecha_i']) && $form['field_proyecto_fecha_i']['#access']) {
1702    $output .= drupal_render($form['field_proyecto_fecha_i']);
1703  }
1704  if (isset($form['field_proyecto_fecha_f']) && $form['field_proyecto_fecha_f']['#access']) {
1705    $output .=  drupal_render($form['field_proyecto_fecha_f']);
1706  }
1707  if (isset($form['field_proyecto_status']) && $form['field_proyecto_status']['#access']) {
1708    $output .= drupal_render($form['field_proyecto_status']);
1709  }
1710  if (isset($form['field_proyecto_situacion_p']) && $form['field_proyecto_situacion_p']['#access']) {
1711    $output .= drupal_render($form['field_proyecto_situacion_p']);
1712  }
1713  if (isset($form['field_proyecto_plurianual']) && $form['field_proyecto_plurianual']['#access']) {
1714    $output .= drupal_render($form['field_proyecto_plurianual']);
1715  }
1716  if (isset($form['field_proyecto_monto_anual']) && $form['field_proyecto_monto_anual']['#access']) {
1717    $output .= drupal_render($form['field_proyecto_monto_anual']);
1718  }
1719  if (isset($form['field_proyecto_total']) && $form['field_proyecto_total']['#access']) {
1720    $output .= drupal_render($form['field_proyecto_total']);
1721  }
1722  if (isset($form['field_proyecto_poan']) && $form['field_proyecto_poan']['#access']) {
1723    $output .= drupal_render($form['field_proyecto_poan']);
1724  }
1725  if (is_array($form['#fields_form_ac_d']) && count($form['#fields_form_ac_d'])) {
1726    foreach($form['#fields_form_ac_d'] as $id_a) {
1727      $output .= drupal_render($form[$id_a]);
1728    }
1729  }
1730  $output .= '</fieldset>';
1731
1732  $output .= '<fieldset><legend>' . t('Responsable del Proyecto') . '</legend>';
1733  $output .= '<div id="edit-field-proyecto-ente-nid-nid-wrapper" class="form-item"><label for="edit-field-proyecto-ente-nid-nid">Institucion:</label>' . check_plain($form['#ente_planificador']->title) . '</div>';
1734
1735  //responsables del proyecto
1736  $responsables_proye = variable_get('proyectos_operativos_muestra_responsables', TRUE);
1737  if ($responsables_proye) {
1738    $output .= drupal_render($form['responsables']);
1739  } 
1740
1741  $gerentes = variable_get('proyectos_operativos_muestra_gerentes', TRUE);
1742  if ($gerentes) {
1743    $output .= '<fieldset><legend>' . t('Gerente del Proyecto') . '</legend>';
1744    $output .= '<div id="edit-field-proyecto-ente-nid-nid-wrapper" class="form-item"><label for="edit-field-proyecto-ente-nid-nid">Institucion:</label>' . check_plain($form['#ente_planificador']->title) . '</div>';
1745    if (isset($form['field_proyecto_ente']) && $form['field_proyecto_ente']['#access']) {
1746      $output .= drupal_render($form['field_proyecto_ente']);
1747    }
1748    if (isset($form['field_proyecto_autoridad']) && $form['field_proyecto_autoridad']['#access']) {
1749      $output .= drupal_render($form['field_proyecto_autoridad']);
1750    }
1751    if (isset($form['field_proyecto_lider']) && $form['field_proyecto_lider']['#access']) {
1752      $output .= drupal_render($form['field_proyecto_lider']);
1753    }
1754    if (isset($form['field_proyecto_unidad_a']) && $form['field_proyecto_unidad_a']['#access']) {
1755      $output .= drupal_render($form['field_proyecto_unidad_a']);
1756    }
1757    if (isset($form['field_proyecto_cargo']) && $form['field_proyecto_cargo']['#access']) {
1758      $output .= drupal_render($form['field_proyecto_cargo']);
1759    }
1760    if (isset($form['field_proyecto_telefono']) && $form['field_proyecto_telefono']['#access']) {
1761      $output .= drupal_render($form['field_proyecto_telefono']);
1762    }
1763    if (isset($form['field_proyecto_correo']) && $form['field_proyecto_correo']['#access']) {
1764      $output .= drupal_render($form['field_proyecto_correo']);
1765    }
1766  }
1767  $output .= '</fieldset>';
1768
1769  $pndes = variable_get('proyectos_operativos_muestra_pndes', TRUE);
1770  $mcti = variable_get('proyectos_operativos_muestra_mcti', TRUE);
1771  $count_ac_p = count($form['#fields_form_ac_p']);
1772  $causas = variable_get('proyectos_operativos_muestra_causas_abordadas', TRUE);
1773  $problemas = variable_get('proyectos_operativos_muestra_problemas_abordados', TRUE);
1774  if ($pndes || $mcti || $count_ac_p || $causas || $problemas) {
1775    $output .= '<fieldset><legend>' . t('Área Estrategica') . '</legend>';
1776    if ($pndes) {
1777      $output .= drupal_render($form['field_proyecto_pndes']);
1778    }
1779    if ($mcti) {
1780      $output .= drupal_render($form['field_proyecto_mcti']);
1781    }
1782    if ($count_ac_p) {
1783      foreach($form['#fields_form_ac_p'] as $id_a) {
1784        $output .= drupal_render($form[$id_a]);
1785      }
1786    }
1787    if($problemas || $causas) {
1788      $output .= '<fieldset> Problemas y causas Abordadas';
1789      if($problemas) {
1790        $output .= drupal_render($form['field_proyect_probl_abord']);
1791      }
1792      if($causas) { 
1793        $output .= drupal_render($form['field_proyect_cau_abord']);
1794      }
1795      $output .= '</fieldset>';
1796    }
1797    $output .= '</fieldset>';
1798  }
1799  //area estrategica
1800 
1801  //ubicacion internacional
1802  if (variable_get('proyectos_operativos_muestra_ubicaci_interna', TRUE)) {
1803    $output .= '<fieldset id="proyectos_ubicacion"><legend>' . t('Localización del Proyecto') . '</legend>';
1804    $output .= '<fieldset><legend>' . t('Localización Internacional o Nacional') . '</legend>';
1805    $output .=  drupal_render($form['field_proyecto_ubicaci_inter']);
1806  }
1807  $output .= '</fieldset>';
1808  //ubicacion comunal
1809  $codig_comuna = variable_get('proyectos_operativos_muestra_codig_comuna', TRUE);
1810  $ubicacin_comuna = variable_get('proyectos_operativos_muestra_ubicacin_comuna', TRUE);
1811  $nombre_comuna = variable_get('proyectos_operativos_muestra_name_comuna', TRUE);
1812  if($codig_comuna || $ubicacin_comuna || $nombre_comuna) {
1813    $output .= '<fieldset><legend>' . t('Localización Comunal') . '</legend>';
1814    $output .= drupal_render($form['field_proyecto_codigo_comu']);
1815    $output .= drupal_render($form['field_proyecto_nombres_cum']);
1816    $output .= drupal_render($form['field_proyecto_ubicaci_comu']);
1817    $output .= '</fieldset>';
1818  }
1819  $output .= '</fieldset>';
1820 
1821  $output .= drupal_render($form);
1822  return $output;
1823}
1824
1825/**
1826 * Agrega los nuevos campos en el formulario proyecto en la pestanha indicadores
1827 */
1828function theme_proyectos_operativos_mcti_proyecto_indicadores_form($form) {
1829  $output = '';
1830  if ($form['#count_ae'] && $form['#montos_asignados']!= $form['#node']->field_proyecto_monto_anual[0]['value']) {
1831    $format_number = array(
1832      'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
1833      'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
1834      'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
1835    );
1836    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
1837    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
1838    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas con un monto total de @montos_asignados Bs, el cual difiere con el monto asignado en el proyecto para el @title_monto_total_proyecto_year (@monto_proyecto). Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@montos_asignados' => number_format($form['#montos_asignados'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '@title_monto_total_proyecto_year' => $form['#proyecto_fields']['field_proyecto_monto_anual']['widget']['label'], '@monto_proyecto' => number_format($form['#node']->field_proyecto_monto_anual[0]['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']), '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
1839    $output .= '<div id="mensaje-mostrar-monto" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
1840  }
1841  if ($form['#count_ae'] && $fechas_validacion['inicio'] && $fechas_validacion['fin'] && ($fechas_validacion['inicio_time'] < $fechas_validacion['inicio_current_time'] || $fechas_validacion['fin_current_time'] < $fechas_validacion['fin_time'])) {
1842    $link_acciones = l(t('Modificar Acciones específicas'), 'proyectosopedit/' . $form['#node']->nid . '/ae');
1843    $link_proyecto = l(t('Modificar Monto del Proyecto'), 'proyectosopedit/' . $form['#node']->nid);
1844    $mensaje_mostrar = t('Existen @count_ae Acciones Específicas asignadas que difieren con la @title_fecha_de_inicio o @title_fecha_de_final del Proyecto. Modifique los montos de las Acciones Específicas en !link_acciones o el monto del proyecto !link_proyecto para poder cerrar el proyecto operativo @nombre_proyecto', array('@count_ae' => $form['#count_ae'], '@title_fecha_de_inicio' => $form['#proyecto_fields']['field_proyecto_fecha_i']['widget']['label'], '@title_fecha_de_final' => $form['#proyecto_fields']['field_proyecto_fecha_f']['widget']['label'], '!link_acciones' => $link_acciones, '!link_proyecto' => $link_proyecto, '@nombre_proyecto' => $form['#node']->titulo_asignado,));
1845    $output .= '<div id="mensaje-mostrar-time" class="mensaje mensaje-mostrar" style="color:red;font-weight: bold;">' . $mensaje_mostrar . '</div>';
1846  }
1847  if (variable_get('proyectos_operativos_muestra_enunciado_problema', TRUE)) {
1848    $output .= '<fieldset><legend>' . t('Enunciado del Problema') . '</legend>' . drupal_render($form['field_proyecto_causas']) . drupal_render($form['field_proyecto_problemas']) . drupal_render($form['field_proyecto_consecuencias']);
1849    if (count($form['#fields_form_ip_in'])) {
1850      foreach($form['#fields_form_ip_in'] as $id_c) {
1851        $output .= drupal_render($form[$id_c]);
1852      }
1853    }
1854    $output .= '</fieldset>';
1855  }
1856  if (variable_get('proyectos_operativos_muestra_justicacion', TRUE)) {
1857    $output .= '<fieldset><legend>' . t('Justificación del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_justificacion']);
1858    if (count($form['#fields_form_ip_ju'])) {
1859      foreach($form['#fields_form_ip_ju'] as $id_c) {
1860        $output .= drupal_render($form[$id_c]);
1861      }
1862    }
1863    $output .= '</fieldset>';
1864  }
1865  if (variable_get('proyectos_operativos_muestra_alcance', TRUE)) {
1866    $output .= '<fieldset><legend>' . t('Alcance del Proyecto') . '</legend>' . drupal_render($form['field_proyecto_alcance']);
1867    if (count($form['#fields_form_ip_al'])) {
1868      foreach($form['#fields_form_ip_al'] as $id_c) {
1869        $output .= drupal_render($form[$id_c]);
1870      }
1871    }
1872    $output .= '</fieldset>';
1873  }
1874  $sa = variable_get('proyectos_operativos_muestra_sa', TRUE);
1875  $so = variable_get('proyectos_operativos_muestra_so', TRUE);
1876  if ($sa || $so) {
1877    $output .= drupal_render($form['indicador']);
1878  }
1879  $output .= '<fieldset><legend>' . t('Indicador del resultado del Proyecto') . '</legend>' ;
1880  $output .= drupal_render($form['field_proyecto_descripcion_bien']);
1881  $output .= drupal_render($form['field_proyecto_so_cuantificacion']);
1882  $output .= drupal_render($form['field_proyecto_unidadm']);
1883  if (isset($form['field_proyecto_meta_m']) && $form['field_proyecto_meta_f']) {
1884    $output .= '<div id="meta-unidm-pers"><table id="unidm-persona" style="width:400px"><tr><th>' . $form['field_proyecto_meta_m']['#title'] . '</th><th>' . $form['field_proyecto_meta_f']['#title'] . '</th><th>' . t('Total') . '</th></tr><tr>';
1885    $form['field_proyecto_meta_m'][0]['value']['#title'] = '';
1886    $form['field_proyecto_meta_f'][0]['value']['#title'] = '';
1887    $total = $form['field_proyecto_meta_m'][0]['#value']['value'] + $form['field_proyecto_meta_f'][0]['#value']['value'];
1888    $output .= '<td>' . drupal_render($form['field_proyecto_meta_m']) . '</td>';
1889    $output .= '<td>' . drupal_render($form['field_proyecto_meta_f']) . '</td>';
1890   
1891    $output .= '<td style="width:100px; text-align: center"><div class="unidad_personas_total">' . number_format($total, $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']) . '</div></td></tr></table></div>';
1892  }
1893
1894  $output .= '<span title="Este campo es obligatorio." class="form-required" style="margin-left: 280px; position: absolute;">*</span>' . drupal_render($form['field_proyecto_meta_fisica']);
1895
1896  if (count($form['#fields_form_ip_re'])) {
1897    foreach($form['#fields_form_ip_re'] as $id_c) {
1898      $output .= drupal_render($form[$id_c]);
1899    }
1900  }
1901  $output .= '</fieldset>';
1902  //agregando el efecto hide y show
1903  drupal_add_js(drupal_get_path('module', 'proyectos_operativos_mcti') . '/js/proyectos_operativos_mcti_generales.js');
1904  $form['field_tipo_factores']['value']['#attributes'] = array(
1905     'class' => ' field_tipo_factores',
1906     'onchange' => ";ocultarCampo('field_tipo_factores', 'field_factor_impact_multifc');",
1907  );
1908  $form['field_factor_segun_origen']['value']['#attributes'] = array(
1909     'class' => ' field_factor_segun_origen',
1910     'onchange' => ";ocultarCampo('field_factor_segun_origen', 'field_factor_impact_multiog');",
1911  );
1912  $form['field_factor_impact_multifc']['#prefix'] = '<div class="field_factor_impact_multifc">';
1913  $form['field_factor_impact_multifc']['#suffix'] = '</div>';
1914  $form['field_factor_impact_multiog']['#prefix'] = '<div class="field_factor_impact_multiog">';
1915  $form['field_factor_impact_multiog']['#suffix'] = '</div>';
1916
1917  //agregando la sesion Impacto Ambiental del Proyecto
1918  $arreglo['impacto']['factor1'] = array(
1919    'field_factor_naturaleza' => 'field_factor_naturaleza',
1920    'field_factor_intensidad' => 'field_factor_intensidad',
1921    'field_factor_momento' => 'field_factor_momento',
1922    'field_factor_persistencia' => 'field_factor_persistencia',
1923    'field_factor_reversibilidad' => 'field_factor_reversibilidad',
1924  );
1925  $arreglo['impacto']['factor2'] = array(
1926    'field_factor_extension' => 'field_factor_extension',
1927    'field_factor_sinergismo' => 'field_factor_sinergismo',
1928    'field_factor_acumulacion' => 'field_factor_acumulacion',
1929    'field_factor_relacion' =>'field_factor_relacion',
1930    'field_factor_recuperabilidad' => 'field_factor_recuperabilidad',
1931  );
1932  $arreglo['impacto']['factor3'] = array(
1933    'field_factor_importancia' => 'field_factor_importancia',
1934    'field_factor_medids_impact' => 'field_factor_medids_impact',
1935  );
1936  $arreglo['impacto']['tipo'] = array(
1937    'field_tipo_factores' => 'field_tipo_factores',
1938    'field_factor_impact_multifc' => 'field_factor_impact_multifc',
1939    'field_factor_segun_origen' => 'field_factor_segun_origen',
1940    'field_factor_impact_multiog' => 'field_factor_impact_multiog',
1941  );
1942  if (variable_get('proyectos_operativos_muestra_impacto_ambiental', TRUE)) {
1943    $output_fa = '<table><tr>';
1944    $output_fb = '<tr>';
1945    $output_fc = '<tr>';
1946    $output .= '<fieldset><legend>' . t('Impacto Ambiental del Proyecto') . '</legend>';
1947    if (count($form['#proyectos_operativos_fields'])) {
1948      foreach ($form['#proyectos_operativos_fields'] as $key => $id_c) {
1949        if (array_key_exists($id_c,  $arreglo['impacto']['factor1'])) {
1950          $output_fa .= '<th> '. $form[$id_c]['#title'] .'</th>';
1951        }
1952        if (array_key_exists($id_c,  $arreglo['impacto']['factor2'])) {
1953          $output_fb .= '<th> '. $form[$id_c]['#title'] .'</th>';
1954        }
1955        if (array_key_exists($id_c,  $arreglo['impacto']['factor3'])) {
1956          $row = '';
1957          if ($id_c == 'field_factor_medids_impact') {
1958            $row = 'colspan = 4';
1959          }
1960          $output_fc .= '<th '.$row.'>'. $form[$id_c]['#title'] .'</th>';
1961        }
1962      }
1963      $output_fa .= '</tr><tr>';
1964      $output_fb .= '</tr><tr>';
1965      $output_fc .= '</tr><tr>';
1966      foreach ($form['#proyectos_operativos_fields'] as $key => $id_c) {
1967        if (array_key_exists($id_c,  $arreglo['impacto']['tipo'])) {
1968          $output1 .= drupal_render($form[$id_c]);
1969        }
1970        //eliminando los labels de los campos
1971        unset($form[$id_c]['value']['#title']);
1972        unset($form[$id_c][0]['value']['#title']);
1973        if (array_key_exists($id_c,  $arreglo['impacto']['factor1'])) {
1974          $output_fa .= '<td>'.drupal_render($form[$id_c]).'</td>';
1975        }
1976        if (array_key_exists($id_c,  $arreglo['impacto']['factor2'])) {
1977          $output_fb .= '<td>'.drupal_render($form[$id_c]).'</td>';
1978        }
1979        if (array_key_exists($id_c,  $arreglo['impacto']['factor3'])) {
1980          $row = '';
1981          if ($id_c == 'field_factor_medids_impact') {
1982            $row = 'colspan = 4';
1983          }
1984          $output_fc .= '<td '.$row.'>'.drupal_render($form[$id_c]).'</td>';
1985        }
1986      }
1987      $output_fa .= '</tr>';
1988      $output_fb .= '</tr>';
1989      $output_fc .= '</tr></table>';
1990      $output2 = $output_fa . $output_fb . $output_fc;
1991      $output .= '<fieldset><legend>' . t('Tipo de impacto') . '</legend>';
1992      $output1.= '<div id="wrapper_field_tipo_factores"></div>';
1993      $output1 .= '<div id="wrapper_field_factor_segun_origen"></div>';
1994      $output .= $output1 . '</fieldset>';
1995      $output .= '<fieldset><legend>' . t('Caracterización cualitativa de los efectos') . '</legend>';
1996      $output .= $output2 . '</fieldset>';
1997    }
1998    $output .= '</fieldset>';
1999  }
2000  //Balance Estimado Nacional de Servicios Energéticos
2001  if (variable_get('proyectos_operativos_muestra_servicios_balance', TRUE)) {
2002    $output .= '<div>' . drupal_render($form['balance']) . '</div>';
2003  }
2004  //Programacion anual por consumidor
2005  if (variable_get('proyectos_operativos_muestra_programacion_anual', TRUE)) {
2006    $output .= '<div>' . drupal_render($form['programacion']) . '</div>';
2007  }
2008  $output .= drupal_render($form);
2009  return $output;
2010}
2011
2012/**
2013 * Agrega mas campos
2014 */
2015function proyectos_operativos_mcti_proyecto_generales_agrega_talento_js_util($tipo) {
2016  $arreglov['talento'] = array(
2017    'field_proyecto_institucionth' => 'field_proyecto_institucionth',
2018    'field_proyecto_nombres_a' => 'field_proyecto_nombres_a',
2019    'field_proyecto_cargo_th' => 'field_proyecto_cargo_th',
2020    'field_proyecto_rol_th' => 'field_proyecto_rol_th',
2021    'field_proyecto_esfuerzo' => 'field_proyecto_esfuerzo',
2022    'field_proyecto_formacion' => 'field_proyecto_formacion',
2023  );
2024  $arreglov['capacidades'] = array(
2025    'field_proyecto_institucion_alc' => 'field_proyecto_institucion_alc',
2026    'field_proyecto_infraestructura' => 'field_proyecto_infraestructura',
2027    'field_proyecto_equipos' => 'field_proyecto_equipos',
2028    'field_proyecto_insumos' => 'field_proyecto_insumos',
2029    'field_proyectos_servicios' => 'field_proyectos_servicios',
2030  );
2031  $arreglov['beneficiario'] = array(
2032    'field_proyecto_beneficiario' => 'field_proyecto_beneficiario',
2033    'field_proyectos_masculino_d' => 'field_proyectos_masculino_d',
2034   // 'field_proyectos_femenino_d' => 'field_proyectos_femenino_d',
2035  //  'field_proyectos_masculino_i' => 'field_proyectos_masculino_i',
2036    'field_proyectos_femenino_i' => 'field_proyectos_femenino_i',
2037  );
2038  $labels = array(
2039    'field_proyecto_beneficiario' => 'Beneficiario ',
2040    'field_proyectos_masculino_d' => 'Número estimado de beneficiarios masculinos',
2041    'field_proyectos_femenino_i' => 'Número estimado de beneficiarios femeninos',
2042  );
2043  if (array_key_exists($tipo, $arreglov)) {
2044    $arreglo = $arreglov[$tipo];
2045  }
2046  else {
2047    drupal_not_found();
2048  }
2049  $cantidad = intval($_POST['cantidad_' . $tipo]) > 0 ? intval($_POST['cantidad_' . $tipo]) : 0;
2050  $form_state = array('submitted' => FALSE);
2051  $form_build_id = $_POST['form_build_id'];
2052  // Add the new element to the stored form. Without adding the element to the
2053  // form, Drupal is not aware of this new elements existence and will not
2054  // process it. We retreive the cached form, add the element, and resave.
2055  $form = form_get_cache($form_build_id, $form_state);
2056  $node_type = content_types('proyectos_operativos');
2057  $fields = $node_type['fields'];
2058  foreach ($arreglo as $field_id => $field) {
2059    $fields_extra_form1[] = $field_id;
2060    $prefixC .= '<th>' . $labels[$field_id] . '</th>';
2061  }
2062  $sumas['beneficiarios'] = array();
2063  $cantidad++;
2064  if ($tipo == 'talento' || $tipo == 'capacidades') {
2065    for ($i = 0; $i < $cantidad; $i++) {
2066      $prefix = '';
2067      if ($i == 0) {
2068        $prefix = '<table align="center"><tr>' . $prefixC . '</tr><tr><td>';
2069      }
2070      else {
2071        $prefix .= '<tr><td>';
2072      }
2073      $aux = '';
2074      $aui = '';
2075      foreach ($arreglo as $field_id => $field) {
2076        $new_form[$field_id . '_' . $i] = array(
2077          '#type' => 'textfield',
2078          '#size' => 10,
2079          '#maxlength' => 255,
2080          '#prefix' => $prefix,
2081          '#suffix' => '</td>',
2082        );
2083        if ($field_id == 'field_proyecto_esfuerzo') {
2084          $form[$field_id . '_' . $i]['#element_validate'] = array('proyectos_operativos_number_integer_validate2',);
2085        }
2086        $aux = $field_id;
2087        $aui = $i;
2088        $prefix = '<td>';
2089      }
2090      $new_form[$aux . '_' . $aui]['#suffix'] .= '</tr>';
2091    }
2092    $new_form[$aux . '_' . $aui]['#suffix'] .= '</table>';
2093    $new_form['cantidad_' . $tipo] = array('#type' => 'hidden', '#value' => $cantidad);
2094  }
2095  elseif ($tipo == 'beneficiario') {
2096    $prefixC .= '<th>' . t('Total') . '</th>';
2097    $vid = variable_get('proyectos_operativos_extra_bene', 0);
2098    $tree = taxonomy_get_tree($vid);
2099    $options = array();
2100    $options[''] = t('Seleccionar');
2101    if ($tree) {
2102      foreach ($tree as $term) {
2103        $options[$term->name] = $term->name;
2104      }
2105    }
2106    for ($i = 0; $i < $cantidad; $i++) {
2107      $subtotal = 0;
2108      $prefix = '';
2109      if ($i == 0) {
2110        $prefix = '<table align="center"><tr>' . $prefixC . '</tr><tr><td>';
2111      }
2112      else {
2113        $prefix .= '<tr><td>';
2114      }
2115      $aux = '';
2116      $aui = '';
2117      foreach ($arreglo as $field_id => $field) {
2118        $_POST[$field_id . '_' . $i] = str_replace($format_number['thousands_sep'], '', $_POST[$field_id . '_' . $i]);
2119        $valor = intval($_POST[$field_id . '_' . $i]) > 0 ? intval($_POST[$field_id . '_' . $i]) : 0;
2120        if ($field_id == 'field_proyecto_beneficiario') {
2121          $new_form[$field_id . '_' . $i] = array(
2122            '#type' => 'select',
2123            '#default_value' => $valor,
2124            '#options' => $options,
2125            '#prefix' => $prefix,
2126            '#suffix' => '</td>',
2127          );
2128        }
2129        else {
2130          $new_form[$field_id . '_' . $i] = array(
2131            '#type' => 'textfield',
2132            '#default_value' => $valor,
2133            '#size' => 10,
2134            '#maxlength' => 255,
2135            '#prefix' => $prefix,
2136            '#suffix' => '</td>',
2137          );
2138        }
2139
2140        if ($field_id != 'field_proyecto_beneficiario') {
2141          if (!isset($total_arreglo[$field_id])) {
2142            $total_arreglo[$field_id] = 0;
2143          }
2144          $subtotal += (int) $valor;
2145          $totales += (int) $valor;
2146          $total_arreglo[$field_id] += (int) $valor;
2147          $sumas['beneficiarios']['beneficiario_' . $i] = 'beneficiario_' . $i;
2148          $new_form[$field_id . '_' . $i]['#element_validate'] = array('proyectos_operativos_number_integer_validate2',);
2149          $new_form[$field_id . '_' . $i]['#attributes'] = array('class' => 'number beneficiario_' . $i . ' todosbeneficiarios beneficiarios_' . $field_id, 'onchange' => "sumabeneficiario('beneficiario_$i');sumabeneficiario('todosbeneficiarios');sumabeneficiario('beneficiarios_$field_id');");
2150        }
2151        $aux = $field_id;
2152        $aui = $i;
2153        $prefix = '<td align="center">';
2154      }
2155
2156      $new_form[$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiario_' . $i . '_total">' . $subtotal . '</div></td>';
2157      $new_form[$aux . '_' . $aui]['#suffix'] .= '</tr>';
2158    }
2159    $new_form[$aux . '_' . $aui]['#suffix'] .= '<tr align="right"><td><b>' . t('TOTAL DE BENEFICIARIOS') . '</b></td>';
2160    foreach ($arreglo as $field_id => $field) {
2161      if ($field_id != 'field_proyecto_beneficiario') {
2162        $sumas['beneficiarios']['beneficiarios_' . $field_id] = 'beneficiarios_' . $field_id;
2163        $new_form[$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="beneficiarios_' . $field_id . '_total">' . $total_arreglo[$field_id] . '</div></td>';
2164      }
2165    }
2166    $sumas['beneficiarios']['todosbeneficiarios'] = 'todosbeneficiarios';
2167    $sumas['beneficiarios']['empleos_generados'] = 'empleos_generados';
2168    $new_form[$aux . '_' . $aui]['#suffix'] .= '<td align="center"><div class="todosbeneficiarios_total">' . $totales . '</div></td></tr>';
2169    $new_form[$aux . '_' . $aui]['#suffix'] .= '</table>';
2170    $new_form['cantidad_' . $tipo] = array('#type' => 'hidden', '#value' => $cantidad);
2171  }
2172  $form[$tipo] = $new_form;
2173  form_set_cache($form_build_id, $form, $form_state);
2174  $form += array(
2175    '#post' => $_POST,
2176    '#programmed' => FALSE,
2177  );
2178  // Rebuild the form.
2179  $form = form_builder($_POST['form_id'], $form, $form_state);
2180  // Render the new output.
2181  $new_form = $form[$tipo];
2182
2183  if ($tipo == 'talento' || $tipo == 'capacidades') {
2184    for ($i = 0; $i < $cantidad; $i++) {
2185      if ($i == 0) {
2186        $prefix = '<table align="center"><tr>' . $prefixC . '</tr><tr><td>';
2187      }
2188      foreach($arreglo as $field_id => $field) {
2189        $new_form[$field_id . '_' . $i] = $form[$tipo][$field_id . '_' . $i];
2190        if ($prefix != '') {
2191          $new_form[$field_id . '_' . $i]['#prefix'] = $prefix;
2192        }
2193        $prefix = '';
2194        $aux = $field_id;
2195        $aui = $i;
2196        $new_form[$aux . '_' . $aui] = $form[$tipo][$aux . '_' . $aui];
2197      }
2198      $new_form[$aux . '_' . $aui] = $form[$tipo][$aux . '_' . $aui];
2199    }
2200    $new_form[$aux . '_' . $aui]['#suffix'] .= '</table>';
2201    $new_form['cantidad_' . $tipo] = array('#type' => 'hidden', '#value' => $cantidad);
2202  }
2203
2204  $new_form['cantidad_' . $tipo] = $form[$tipo]['cantidad_' . $tipo];
2205  unset($new_form['cantidad_' . $tipo]['#suffix']);
2206  unset($new_form['#prefix'], $new_form['#suffix']); // Prevent duplicate wrappers.
2207  //unset($new_form['agrega_' . $tipo]);
2208  $output = drupal_render($new_form);
2209
2210  drupal_add_js($sumas, 'setting');
2211  $output .= drupal_get_js();
2212
2213  print drupal_to_js(array('data' => $output, 'status' => true));
2214  exit();
2215}
2216
2217/**
2218 * Agrega mas campos para indicadores form
2219 */
2220function proyectos_operativos_mcti_agrega_indicadores_js_util($tipo) {
2221  $arreglov['balance'] = array(
2222    'field_balnc_progrmn_anu' => 'field_balnc_progrmn_anu',
2223    'field_balance_fuente' => 'field_balance_fuente',
2224    'field_balanc_tipofuent' => 'field_balanc_tipofuent',
2225    'field_balanc_tipoprod' => 'field_balanc_tipoprod',
2226    'field_balanc_unidmed' => 'field_balanc_unidmed',
2227    'field_balanc_capacid' => 'field_balanc_capacid',
2228    'field_balanc_anho' => 'field_balanc_anho',
2229  );
2230  $arreglov['programacion'] = array(
2231    'field_progrmcn_anual_prog' => 'field_progrmcn_anual_prog',
2232    'field_progrmcn_anual_unid' => 'field_progrmcn_anual_unid',
2233    'field_progrmcn_anual_cap' => 'field_progrmcn_anual_cap',
2234    'field_progrmcn_anual_anho' => 'field_progrmcn_anual_anho',
2235  );
2236  if (array_key_exists($tipo, $arreglov)) {
2237    $arreglo = $arreglov[$tipo];
2238  }
2239  else {
2240    drupal_not_found();
2241  }
2242  //anho para las opciones balance y programacion
2243  $current_year = date("Y");
2244  $years[0] = t('Seleccione');
2245  for ($i = $current_year - 10; $i <= $current_year; $i++) {
2246    $years[$i] = $i;
2247  }
2248
2249  $form_state = array('submitted' => FALSE);
2250  $form_build_id = $_POST['form_build_id'];
2251  // Add the new element to the stored form. Without adding the element to the
2252  // form, Drupal is not aware of this new elements existence and will not
2253  // process it. We retreive the cached form, add the element, and resave.
2254  $form = form_get_cache($form_build_id, $form_state);
2255  $node_type = content_types('proyectos_operativos');
2256  $fields = $node_type['fields'];   
2257  $prefixC = '';
2258  $fields_extra_form1 = array();
2259  foreach ($arreglo as $field_id => $field) {
2260    $fields_extra_form1[] = $field_id;
2261    $prefixC .= '<th>' . $fields[$field_id]['widget']['label'] . '</th>';
2262  }
2263  $cantidad = intval($_POST['cantidad_'.$tipo]) > 0 ? intval($_POST['cantidad_'.$tipo]) : 0;
2264  $cantidad++;
2265  $prefix = '';
2266  $aux = '';
2267  $aui = '';
2268
2269  for ($i = 0; $i < $cantidad; $i++) {
2270    if ($i == 0) {
2271      $prefix = '<table><tr>' . $prefixC . '</tr><tr><td>';
2272    }
2273    else {
2274      $prefix .= '<tr><td>';
2275    }
2276    foreach ($arreglo as $field_id => $field) {
2277      if (($field_id == 'field_progrmcn_anual_cap' || $field_id == 'field_balanc_capacid') && ($tipo == 'balance' || $tipo == 'programacion')) {
2278        $new_form[$field_id . '_' . $i] = array(
2279         '#type' => 'textfield',
2280         '#size' => $fields[$field_id]['size'],
2281         '#maxlength' => $fields[$field_id]['max_length'],   
2282         '#prefix' => $prefix,
2283         '#suffix' => '</td>',
2284       );
2285     }
2286     elseif (($field_id == 'field_balanc_anho' || $field_id == 'field_progrmcn_anual_anho') && ($tipo == 'balance' || $tipo == 'programacion')) {
2287       $new_form[$field_id . '_' . $i] = array(
2288         '#type' => 'select',
2289         '#maxlength' => $fields[$field_id]['max_length'],
2290         '#required' => $fields[$field_id]['required'],
2291         '#options' => $years,
2292         '#prefix' => $prefix,
2293         '#suffix' => '</td>',
2294       );
2295     }
2296     else {
2297         $options = optionwidgets_options($fields[$field_id], FALSE);
2298         $new_form[$field_id . '_' . $i] = array(
2299           '#type' => 'select',
2300           '#options' => $options,
2301           '#prefix' => $prefix,
2302           '#suffix' => '</td>',
2303         );
2304       }
2305       $aux = $field_id;
2306       $aui = $i;
2307       $prefix = '<td>';
2308     }
2309     $new_form[$aux . '_' . $aui]['#suffix'] .= '</tr>';
2310   }
2311   $new_form[$aux . '_' . $aui]['#suffix'] .= '</table>';
2312   $new_form['cantidad_'.$tipo] = array('#type' => 'hidden', '#value' => $cantidad);
2313   
2314   $form[$tipo] = $new_form;
2315   form_set_cache($form_build_id, $form, $form_state);
2316   $form += array(
2317     '#post' => $_POST,
2318     '#programmed' => FALSE,
2319   );
2320   // Rebuild the form.
2321   $form = form_builder($_POST['form_id'], $form, $form_state);
2322   // Render the new output.
2323   $new_form = $form[$tipo];
2324   unset($new_form['#prefix'], $new_form['#suffix']); // Prevent duplicate wrappers.
2325   $output = drupal_render($new_form);
2326   print drupal_to_js(array('data' => $output, 'status' => true));
2327   exit();
2328}
2329
2330/**
2331 * Carga los datos de los responsables del proyecto
2332 */
2333function proyectos_operativos_mcti_proyecto_basico_form_responsables_js_util($tipo) {
2334  $form_state = array(
2335    'submitted' => FALSE,
2336  );
2337  $form_build_id = $_POST['form_build_id'];
2338  // Add the new element to the stored form. Without adding the element to the
2339  // form, Drupal is not aware of this new elements existence and will not
2340  // process it. We retreive the cached form, add the element, and resave.
2341  $form = form_get_cache($form_build_id, $form_state);
2342 
2343  $nid = $_POST['field_proyecto_ente'];
2344  $node_type = content_types('proyectos_operativos');
2345  $fields = $node_type['fields'];
2346  $query_ins = db_query("SELECT nid, title FROM {node} WHERE type='ente_planificador' AND status=1");
2347  while ($row = db_fetch_object($query_ins)) {
2348    $instituciones[$row->nid] = $row->title;
2349  }
2350 
2351  $new_form['responsables'] = array(
2352    '#title' => t(''),
2353    '#type' => 'fieldset',
2354  );
2355  /*$new_form['responsables']['field_proyecto_ente'] = array(
2356    '#title' => t('Insitución'),
2357    '#type' => 'select',
2358    '#options' => $instituciones,
2359    '#ahah' => array(
2360      'path' => 'proyectos_operativos_mcti_proyecto_basico_form_responsables/responsables',
2361      'wrapper' => 'wrapper-proyectos-resposab',
2362      'method' => 'replace',
2363      'progress' => array('type' => 'throbber', 'message' => t('Please wait...')),
2364    ),
2365    '#prefix' => '<div id="field_proyecto_ente_datos_basicos">',
2366    '#suffix' => '</div>',
2367  );
2368      */
2369  $arreglo = array();
2370  $tipos = array(
2371    'gerente' => 'gerente',
2372    'tecnico' => 'tecnico',
2373    'registrador' => 'registrador',
2374    'administrativo' => 'administrativo',
2375  );
2376  $arreglo['gerente'] = array(
2377    0 => 'field_proyecto_nombre_gere',
2378    1 => 'field_proyecto_cedul_gere',
2379    2 => 'field_proyecto_corre_gere',
2380    3 => 'field_proyecto_telef_gere',
2381  );
2382  $arreglo['tecnico'] = array(
2383    0 => 'field_proyecto_nom_r_tec',
2384    1 => 'field_proyecto_ced_r_tec',
2385    2 => 'field_proyecto_cor_r_tec',
2386    3 => 'field_proyecto_tel_r_tec',
2387    4 => 'field_proyecto_und_r_tec',
2388  );
2389  $arreglo['registrador'] = array(
2390    0 => 'field_proyecto_nom_r_reg',
2391    1 => 'field_proyecto_ced_r_reg',
2392    2 => 'field_proyecto_cor_r_reg',
2393    3 => 'field_proyecto_tel_r_reg',
2394  );
2395  $arreglo['administrativo'] = array(
2396    0 => 'field_proyecto_nom_r_adm',
2397    1 => 'field_proyecto_ced_r_adm',
2398    2 => 'field_proyecto_cor_r_adm',
2399    3 => 'field_proyecto_tel_r_adm',
2400    4 => 'field_proyecto_und_r_adm',
2401  ); 
2402 
2403  $query['gerente'] = db_query("SELECT DISTINCT(pp.vid), pp.field_proyecto_nombre_gere_value as field_proyecto_nombre_gere, pp.field_proyecto_cedul_gere_value as field_proyecto_cedul_gere FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.vid=pp.vid AND n.status=1 ORDER BY pp.vid asc", $nid);
2404  $query['tecnico'] = db_query("SELECT DISTINCT(pp.vid), pp.field_proyecto_nom_r_tec_value as field_proyecto_nom_r_tec, pp.field_proyecto_ced_r_tec_value as field_proyecto_ced_r_tec FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.vid=pp.vid AND n.status=1 ORDER BY pp.vid asc", $nid);
2405  $query['registrador'] = db_query("SELECT DISTINCT(pp.vid), pp.field_proyecto_nom_r_reg_value as field_proyecto_nom_r_reg, pp.field_proyecto_ced_r_reg_value as field_proyecto_ced_r_reg FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.vid=pp.vid AND n.status=1 ORDER BY pp.vid asc", $nid);
2406  $query['administrativo'] = db_query("SELECT DISTINCT(pp.vid), pp.field_proyecto_nom_r_adm_value as field_proyecto_nom_r_adm, pp.field_proyecto_ced_r_adm_value as field_proyecto_ced_r_adm FROM {node} as n INNER JOIN {proyectos_operativos} as p ON n.nid=p.nid INNER JOIN {content_type_proyectos_operativos} as pp ON pp.nid = p.nid WHERE n.type='proyectos_operativos' AND p.ente=%d AND n.vid=pp.vid AND n.status=1 ORDER BY pp.vid asc", $nid);
2407
2408  foreach ($tipos as $tip) {
2409    $options = array();
2410    $options[0] = t('Seleccione');
2411    $count = 0;
2412    $prefixC = '';
2413    while ($row = db_fetch_object($query[$tip]) ) {
2414      if ($row->$arreglo[$tip][0] != null || $row->$arreglo[$tip][1] != null) {
2415        $options[$row->vid] = $row->$arreglo[$tip][0] . '('. $row->$arreglo[$tip][1] .')';
2416      }
2417    }
2418    $options[$row->vid + 1] = t('Nuevo');
2419    $new_form['responsables']['default_'.$tip] = array(
2420      '#type' => 'select',
2421      '#title' => t('Cargar datos del '.$tip),
2422      '#options' => $options,
2423      '#prefix' => '<fieldset id="wrapper-'.$tip.'-datos"><legend>' . t('Responsable '.$tip ) . '</legend>',
2424    );
2425    $new_form['responsables']['default_'.$tip]['#prefix'] .= '<div id="default_'.$tip.'_select">';
2426    $new_form['responsables']['default_'.$tip]['#suffix'] .= '</div>';
2427    if (count($fields)) {
2428      foreach ($arreglo[$tip] as $field_id => $field) {
2429        $prefixC .= '<th>' . $fields[$field]['widget']['label'] . '</th>';
2430      }
2431      foreach ($arreglo[$tip] as $field_id => $field) {
2432        $prefix = '';
2433        if ($count == 0) {
2434          $prefix = '<div id="default_'.$tip.'"><table><tr>' . $prefixC . '</tr><tr><td>';
2435        }
2436        else {
2437          $prefix .= '<td>';
2438        }
2439        $new_form['responsables'][$field] = array(
2440          '#type' => 'textfield',
2441          '#required' => $fields[$field]['required'],
2442          '#maxlength' => $fields[$field]['max_length'],
2443          '#size' => $fields[$field]['size'],
2444          '#weight' => $fields[$field]['weight'],
2445          '#description' => $fields[$field]['description'],
2446          '#prefix' => $prefix,
2447          '#suffix' => '</td>',
2448        );
2449        $aux = $field;
2450        $count++;
2451      }
2452      $new_form['responsables'][$aux]['#suffix'] .= '</tr>';
2453      $new_form['responsables'][$aux]['#suffix'] .= '</table></div></fieldset>';
2454    }
2455  }
2456 
2457  $form[$tipo] = $new_form;
2458  form_set_cache($form_build_id, $form, $form_state);
2459  $form += array(
2460    '#post' => $_POST,
2461    '#programmed' => FALSE,
2462  );
2463  // Rebuild the form.
2464 
2465  $form = form_builder($_POST['form_id'], $form, $form_state);
2466  // Render the new output.
2467  $new_form = $form[$tipo];
2468  unset($new_form['#prefix'], $new_form['#suffix']); // Prevent duplicate wrappers.
2469  $output = drupal_render($new_form);
2470  print drupal_to_js(array('data' => $output, 'status' => true));
2471  exit();
2472}
2473
2474/**
2475 * Implementation of proyectos_operativos_search_ac_display().
2476 * Muestra la lista de proyectos disponibles.
2477 */
2478function proyectos_operativos_mcti_search_ac_display() {
2479  global $user;
2480  $current_time = time();
2481  $tipo_plan = 'proyectos_operativos_formular';
2482  $mi_fecha = ente_planificador_user_acceso_proceso($tipo_plan, 2);
2483  $fecha = FALSE;
2484  $ente_planificador = 0;
2485  $ente = usuario_tiene_ente($user->uid);
2486  if ($ente && $ente->nid) {
2487    $ente_planificador = ente_planificador_leer_ente_planificadores($ente->nid);
2488  }
2489  if ($mi_fecha[1]  + 86399 > $current_time && $mi_fecha[0] < $current_time) {
2490    $fecha = TRUE;
2491  }
2492  if (!$fecha) {
2493    muestra_mensaje($tipo_plan, $ente_planificador);
2494  }
2495  if ($fecha && $ente->nid) {
2496    muestra_mensaje($tipo_plan, $ente_planificador, 0);
2497  }
2498  if ($fecha && (is_numeric($ente_planificador) && user_access('admin all planificador'))) { //usuarios administradores
2499    muestra_mensaje($tipo_plan, $ente_planificador, 0);
2500  }
2501  $rol_macro = variable_get('ActorPlanificadorMacro', 0);
2502  if ($fecha && in_array($rol_macro, array_keys($user->roles))) { //es usuario control
2503    muestra_mensaje($tipo_plan, $ente_planificador, 0);
2504  }
2505  $states = array();
2506  $first_state = 0;
2507  if (module_exists('workflow')) {
2508    $states = _proyectos_operativos_reformula_obtiene_estados();
2509    if ($states['wid']) {
2510      $first_state = _workflow_creation_state($states['wid']);
2511    }
2512  }
2513  $output = drupal_get_form('proyectos_operativos_mcti_search_ac_form');
2514  $mi_ambito = db_result(db_query("SELECT ambito FROM {ente_user_planificador} where usuario = %d", $user->uid));
2515  $inputs = array();
2516  $sql = '';
2517  if (!user_access('admin planificador') && $user->entes) {
2518    $inputs[] = $user->entes;
2519    $inputs[] = variable_get('proyectos_operativos_state_naprobado', NULL);
2520    $sql .= "SELECT ac.nid, ac.year, w.sid, n.created, n.title as nombre, u.name, n.uid, e.title AS ente, ctpo.field_proyecto_titulo_value, ent.ambito, ent.sector, ent.organismo, ent.ente_adscrito, ent.sub_ente, ctpo.field_proyecto_sector_value, ctpo.field_proyecto_pndes_value FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid INNER JOIN {ente_planificador} AS ent ON ac.ente = ent.nid LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid  WHERE ac.ente = %d AND w.sid <> %d";
2521//    $sql .= "SELECT ac.nid, ac.year, w.sid, n.created, n.title as nombre, u.name, n.uid, e.title AS ente FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE ac.ente = %d AND w.sid <> %d";
2522  }
2523  elseif (user_access('admin planificador')) {
2524    $inputs[] = variable_get('proyectos_operativos_state_naprobado', NULL);
2525    $sql .= "SELECT ac.nid, ac.year, ac.ente, w.sid, n.created, n.title as nombre,  u.name, n.uid, e.title AS enten, ctpo.field_proyecto_titulo_value, ent.ambito, ent.sector, ent.organismo, ent.ente_adscrito, ent.sub_ente, ctpo.field_proyecto_sector_value, ctpo.field_proyecto_pndes_value FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid INNER JOIN {ente_planificador} AS ent ON ac.ente = ent.nid LEFT JOIN {content_type_proyectos_operativos} AS ctpo ON ctpo.nid = n.nid AND ctpo.vid = n.vid WHERE w.sid <> %d";
2526//    $sql .= "SELECT ac.nid, ac.year, ac.ente, w.sid, n.created, n.title as nombre,  u.name, n.uid, e.title AS enten FROM {proyectos_operativos} AS ac INNER JOIN {node} AS n ON n.nid = ac.nid INNER JOIN {users} AS u ON u.uid = n.uid INNER JOIN {node} as e ON e.nid = ac.ente INNER JOIN {workflow_node} AS w ON w.nid = ac.nid WHERE w.sid <> %d";
2527    $proyectos_operativos_search_ac_ente = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ente']) ? $_SESSION['proyectos_operativos']['ente'] : 0;
2528    if ($proyectos_operativos_search_ac_ente) {
2529      $inputs[] = $proyectos_operativos_search_ac_ente;
2530      $sql .= ' AND ac.ente = %d';
2531    }
2532  }
2533  $proyectos_operativos_search_ac_anho_creacion = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['anho']) ? $_SESSION['proyectos_operativos']['anho'] : 0;
2534  if ($proyectos_operativos_search_ac_anho_creacion) {
2535    $sql .= ' AND ac.year = %d';
2536    $inputs[] = $proyectos_operativos_search_ac_anho_creacion;
2537  }
2538  //ambito
2539  $proyectos_operativos_search_ac_ambito = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ambito']) ? $_SESSION['proyectos_operativos']['ambito'] : 0;
2540  if ($proyectos_operativos_search_ac_ambito) {
2541    $sql .= ' AND ent.ambito = %d';
2542    $inputs[] = $proyectos_operativos_search_ac_ambito;
2543    if ($supervisor && $nivel1) {
2544      $sql .= ' AND ent.ambito = %d';
2545      $inputs[] = $mi_ambito;
2546    }
2547  }
2548  //sectores
2549  $proyectos_operativos_search_ac_sectores = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['sectores']) ? $_SESSION['proyectos_operativos']['sectores'] : 0;
2550  if ($proyectos_operativos_search_ac_sectores) {
2551    $sql .= ' AND ctpo.field_proyecto_sector_value = %d';
2552    $inputs[] = $proyectos_operativos_search_ac_sectores;
2553  }
2554  //pndes
2555  $proyectos_operativos_search_ac_pndes = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['pndes']) ? $_SESSION['proyectos_operativos']['pndes'] : 0;
2556  if ($proyectos_operativos_search_ac_pndes) {
2557    $sql .= ' AND ctpo.field_proyecto_pndes_value = %d';
2558    $inputs[] = $proyectos_operativos_search_ac_pndes;
2559  }
2560  //ente adscrito
2561  $proyectos_operativos_search_ac_ente_adscrito = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ente_adscrito']) ? $_SESSION['proyectos_operativos']['ente_adscrito'] : 0;
2562  if ($proyectos_operativos_search_ac_ente_adscrito) {
2563    $sql .= ' AND ent.ente_adscrito = %d';
2564    $inputs[] = $proyectos_operativos_search_ac_ente_adscrito;
2565    if ($enlace_f && $nivel3) {
2566      $sql .= ' AND ac.ente = %d';
2567      $inputs[] = $user->ente_adscrito;
2568    }
2569  }
2570  //sub-ente adscrito
2571  $proyectos_operativos_search_ac_sub_ente = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['sub_ente']) ? $_SESSION['proyectos_operativos']['sub_ente'] : 0;
2572  if ($proyectos_operativos_search_ac_sub_ente) {
2573    $sql .= ' AND ac.ente = %d';
2574    $inputs[] = $proyectos_operativos_search_ac_sub_ente;
2575  }
2576
2577  $sql .= ' ORDER BY ac.year DESC, ac.ente';
2578  $header = array();
2579  $cab = 6;
2580  if (user_access('admin planificador')) {
2581    $header[] = array('data' => t('Ente.'));
2582    $cab++;
2583  }
2584  $header[] = array('data' => t('Proyecto'));
2585  $header[] = array('data' => t('Año'));
2586  $header[] = array('data' => t('Estado'));
2587  $header[] = array('data' => t('Fecha de creación'));
2588  $header[] = array('data' => t('Autor'));
2589  $header[] = array('data' => t('Acción'));
2590  $result = db_query($sql, $inputs);
2591  $rows = array();
2592  while($ac = db_fetch_object($result)) {
2593    $row = array();
2594    if (user_access('admin planificador')) {
2595      $row[] = array('data' => l($ac->enten, 'node/' . $ac->ente),);
2596    }
2597    $nombre_proyecto = $ac->field_proyecto_titulo_value ? $ac->field_proyecto_titulo_value : $ac->nombre;
2598    $row[] = array('data' => $nombre_proyecto,);
2599//    $row[] = array('data' => $ac->nombre,);
2600    $row[] = array('data' => $ac->year,);
2601    $estad0 = $ac->sid == $first_state ? t('Ingresado') : $states['states'][$ac->sid];
2602    $row[] = array('data' => $estad0,);
2603    $row[] = array('data' => format_date($ac->created),);
2604    $row[] = array('data' => l($ac->name, 'user/' . $ac->uid),);
2605    $links = array();
2606    drupal_alter('proyecto_obtiene_links', $links, $ac, $fecha);
2607    $row[] = array('data' => theme('item_list', $links),);
2608    $rows[] = $row;
2609  }
2610  if (!count($rows)) {
2611    $row[] = array('data' => t('No existen Proyectos Operativos'), 'colspan' => $cab);
2612    $rows[] = $row;
2613  }
2614  $output .= theme('table', $header, $rows);
2615  if ($fecha) {
2616    $links = array();
2617    drupal_alter('proyecto_obtiene_agregar_links', $links);
2618    $output .= '<div id="ente-planificador-agregar-proyecto">' . theme('item_list', $links) . '</div>';
2619  }
2620  $form['#submit'][] = 'proyectos_operativos_mcti_search_ac_form_submit';
2621  return $output;
2622}
2623
2624/**
2625 * Implementation of proyectos_operativos_search_ac_form().
2626 * Formulario de busqueda de proyecto.
2627 */
2628function proyectos_operativos_mcti_search_ac_form($form_state) {
2629  $form = array();
2630  global $user;
2631  foreach ($user->roles as $id => $name) {
2632    if ($name == 'Supervisor') {
2633      $supervisor = $id;
2634    }
2635    if ($name == 'Enlace Revisor') {
2636      $enlace_r = $id;
2637    }
2638    if ($name == 'Enlace Formulador') {
2639      $enlace_f = $id;
2640    }
2641    if ($name == 'Control') {
2642      $control = $id;
2643    }
2644    if ($name == 'Administrador') {
2645      $admin = $id;
2646    }
2647  }
2648  $nivel1 = db_result(db_query("SELECT ente_planificador FROM {ente_planificador} where tipo = %d", 1));
2649  $nivel2 = db_result(db_query("SELECT ente_planificador FROM {ente_planificador} where tipo = %d", 2));
2650  $nivel3 = db_result(db_query("SELECT ente_planificador FROM {ente_planificador} where tipo = %d", 3));
2651  $nivel4 = db_result(db_query("SELECT ente_planificador FROM {ente_planificador} where tipo = %d", 4));
2652
2653  if (user_access('admin planificador') || $control || ($supervisor && $nivel1) || ($supervisor && $nivel2)) {
2654    $entes = array();
2655    $result = db_query('SELECT e.nid, n.title FROM {ente_planificador} AS e INNER JOIN {node} AS n ON n.nid = e.nid WHERE n.status = 1');
2656    $entes[0] = t('Todos');
2657    while ($ente = db_fetch_object($result)) {
2658      $entes[$ente->nid] = $ente->title;
2659    }
2660    $proyectos_operativos_search_ac_ente = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ente']) ? $_SESSION['proyectos_operativos']['ente'] : 0;
2661    $form['proyectos_operativos_search_ac_ente'] = array(
2662      '#title' => t('Ente Planificador'),
2663      '#type' => 'select',
2664      '#default_value' => $proyectos_operativos_search_ac_ente,
2665      '#options' => $entes,
2666    );
2667  } 
2668  if ($control || ($supervisor && $nivel2) || ($supervisor && $nivel1) || ($supervisor && $nivel3) || ($supervisor && $nivel4) || ($enlace_f && $nivel1) || ($enlace_f && $nivel2) || ($enlace_f && $nivel3) || ($enlace_f && $nivel4) || ($enlace_r && $nivel1) || ($enlace_r && $nivel2) || ($enlace_r && $nivel3)) {
2669    $years = array();
2670    $years[0] = t('Todos');
2671    $current_year = date("Y");
2672    for ($i = $current_year - 10; $i <= $current_year; $i++) {
2673      $years[$i] = $i;
2674    }
2675    $proyectos_operativos_search_ac_anho_creacion = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['anho']) ? $_SESSION['proyectos_operativos']['anho'] : 0;
2676    $form['proyectos_operativos_search_ac_anho_creacion'] = array(
2677      '#title' => t('Proyectos Operativos para el año'),
2678      '#type' => 'select',
2679      '#default_value' => $proyectos_operativos_search_ac_anho_creacion,
2680      '#options' => $years,
2681    );
2682  }
2683  if ($control) {
2684    $vocabulary = variable_get('ente_planificador_sector_Ambitos', 0);
2685    $terms = taxonomy_get_tree($vocabulary);
2686    $ambitos[0] = t('Selecione');
2687    foreach ($terms as $term) {
2688      if ($term->depth == 0) { //si el termino es padre
2689      $ambitos[$term->tid] = $term->name;
2690      }
2691    }
2692    $proyectos_operativos_search_ac_ambito = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ambito']) ? $_SESSION['proyectos_operativos']['ambito'] : 0;
2693    $form['proyectos_operativos_search_ac_ambito'] = array(
2694      '#title' => t('Ambito del ente planificador'),
2695      '#type' => 'select',
2696      '#default_value' => $proyectos_operativos_search_ac_ambito,
2697      '#options' => $ambitos,
2698    );
2699  }
2700  if ($control || ($supervisor && $nivel2)) {
2701    $vocabulary = variable_get('proyectos_operativos_extra_sector', 0);
2702    $proyectos_operativos_search_ac_sectores = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['sectores']) ? $_SESSION['proyectos_operativos']['sectores'] : 0;
2703    $form['proyectos_operativos_search_ac_sectores'] = array(
2704      '#title' => t('Sector social del Proyecto'),
2705      '#type' => 'hierarchical_select',
2706      '#config' => array(
2707        'module' => 'hs_content_taxonomy',
2708        'params' => array(
2709          'vid' => variable_get('proyectos_operativos_extra_sector', 0),
2710          'tid' => 0,
2711          'depth' => 2,
2712        ),
2713        'level_labels' => array(
2714          'status' => 1,
2715          'labels' => array(
2716            1 => t('Sub-Sector'),
2717          ),
2718        ),
2719      ),
2720      '#default_value' => $proyectos_operativos_search_ac_sectores,
2721    );
2722  }
2723  if ($control || ($supervisor && $nivel2) || ($supervisor && $nivel3) || ($supervisor && $nivel4) || ($enlace_f && $nivel1) || ($enlace_f && $nivel2) || ($enlace_f && $nivel3) || ($enlace_f && $nivel4) || ($enlace_r && $nivel1) || ($enlace_r && $nivel2) || ($enlace_r && $nivel3)) {
2724    $vocabulary = variable_get('proyectos_operativos_PNDES', 0);
2725    $terms = taxonomy_get_tree($vocabulary);
2726    $pndes[0] = t('Selecione');
2727    foreach ($terms as $term) {
2728      if ($term->depth == 0) { //si el termino es padre
2729        $pndes[$term->tid] = $term->name;
2730      }
2731    }
2732    $proyectos_operativos_search_ac_pndes = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['pndes']) ? $_SESSION['proyectos_operativos']['pndes'] : 0;
2733    $form['proyectos_operativos_search_ac_pndes'] = array(
2734      '#title' => t('PNDES'),
2735      '#type' => 'select',
2736      '#default_value' => $proyectos_operativos_search_ac_pndes,
2737      '#options' => $pndes,
2738    );
2739  }
2740  if ($control || ($supervisor && $nivel2) || ($supervisor && $nivel1) || ($enlace_r && $nivel2)) {
2741    $nivel = 3; //Ente adscrito
2742    $result = db_query('SELECT e.nid, n.title FROM {ente_planificador} AS e INNER JOIN {node} AS n ON n.nid = e.nid WHERE n.status = 1 AND e.tipo=%d AND e.ente_adscrito != %d', $nivel, 0);
2743    $entes_ad[0] = t('Seleccione');
2744    while ($ente = db_fetch_object($result)) {
2745      $entes_ad[$ente->nid] = $ente->title;
2746    }
2747    $proyectos_operativos_search_ac_ente_adscrito = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['ente_adscrito']) ? $_SESSION['proyectos_operativos']['ente_adscrito'] : 0;
2748    $form['proyectos_operativos_search_ac_ente_adscrito'] = array(
2749      '#title' => t('Ente adscrito a un organismo publico.'),
2750      '#type' => 'select',
2751      '#default_value' => $proyectos_operativos_search_ac_ente_adscrito,
2752      '#options' => $entes_ad,
2753    );
2754  }
2755  if ($control || ($supervisor && $nivel1) || ($supervisor && $nivel2) || ($supervisor && $nivel3) || ($enlace_r && $nivel2) || ($enlace_r && $nivel3)) {
2756    $nivel = 4; //sub-ente planificador adscrito
2757    $result = db_query('SELECT n.nid, n.title FROM {ente_planificador} AS e INNER JOIN {node} AS n ON n.nid = e.nid WHERE n.status = 1 AND e.tipo = %d AND e.sub_ente != %d', $nivel, 0);
2758    $sub_entes[0] = t('Seleccione');
2759    while ($ente = db_fetch_object($result)) {
2760      $sub_entes[$ente->nid] = $ente->title;
2761    }
2762    $proyectos_operativos_search_ac_sub_ente = isset($_SESSION['proyectos_operativos']) && isset($_SESSION['proyectos_operativos']['sub_ente']) ? $_SESSION['proyectos_operativos']['sub_ente'] : 0;
2763    $form['proyectos_operativos_search_ac_sub_ente'] = array(
2764      '#title' => t('Ente adscrito a otro ente adscrito.'),
2765      '#type' => 'select',
2766      '#default_value' => $proyectos_operativos_search_ac_sub_ente,
2767      '#options' => $sub_entes,
2768    );
2769  }
2770  $form['buttons'] = array(
2771    '#prefix' => '<div class="container-inline">',
2772    '#suffix' => '</div>',
2773  );
2774  $form['buttons']['submit'] = array(
2775    '#type' => 'submit',
2776    '#value' => t('Buscar'),
2777  );
2778  $form['#submit'][] = 'proyectos_operativos_mcti_search_ac_form_submit';
2779  return $form;
2780}
2781
2782/**
2783 * Implementation of proyectos_operativos_mcti_search_ac_form_submit().
2784 * cambia el filtro de busqueda de proyectos.
2785 */
2786function proyectos_operativos_mcti_search_ac_form_submit($form, &$form_state) {
2787  $_SESSION['proyectos_operativos'] = array();
2788  if ($form_state['values']['proyectos_operativos_search_ac_ambito']) {
2789    $_SESSION['proyectos_operativos']['ambito'] = $form_state['values']['proyectos_operativos_search_ac_ambito'];
2790  }
2791  if ($form_state['values']['proyectos_operativos_search_ac_sectores']) {
2792    $_SESSION['proyectos_operativos']['sectores'] = $form_state['values']['proyectos_operativos_search_ac_sectores'];
2793  }
2794  if ($form_state['values']['proyectos_operativos_search_ac_pndes']) {
2795    $_SESSION['proyectos_operativos']['pndes'] = $form_state['values']['proyectos_operativos_search_ac_pndes'];
2796  }
2797  if ($form_state['values']['proyectos_operativos_search_ac_ente_adscrito']) {
2798    $_SESSION['proyectos_operativos']['ente_adscrito'] = $form_state['values']['proyectos_operativos_search_ac_ente_adscrito'];
2799  }
2800  if ($form_state['values']['proyectos_operativos_search_ac_sub_ente']) {
2801    $_SESSION['proyectos_operativos']['sub_ente'] = $form_state['values']['proyectos_operativos_search_ac_sub_ente'];
2802  }
2803}
2804
2805/**
2806 * Implementation of hook_menu_alter
2807 */
2808function proyectos_operativos_mcti_menu_alter(&$items) {
2809  //$items['proyectos_operativos']['page callback'] = 'proyectos_operativos_mcti_search_ac_display';
2810  $items['proyectosopedit/%proyectosop/ficha']['page callback'] = '_proyectos_operativos_mcti_proyecto_ficha_proyecto';
2811  $items['proyectosop/%proyectosop/ficha']['page callback'] = '_proyectos_operativos_mcti_proyecto_ficha_proyecto';
2812}
2813
2814/**
2815 * Implementation of _proyectos_operativos_proyecto_financieros().
2816 * Ver datos financieros (proyectos operativos).
2817 */
2818function _proyectos_operativos_mcti_proyecto_ficha_proyecto($proyecto = 0) {
2819  drupal_set_title(t('Ficha del Proyecto'));
2820  return theme('proyectos_operativos_mcti_ficha_proyecto', $proyecto);
2821}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.