source: sipes/0.3-modules/proyectos_operativos_mcti/proyectos_operativos_mcti.module @ 92f109b

stableversion-3.0
Last change on this file since 92f109b was 1d97659, checked in by eramirez <eramirez@…>, 8 años ago

e modifico el modulo

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