source: sipes/0.3-modules/proyectos_operativos_mcti/proyectos_operativos_mcti.module @ 1951ae0f

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

se modifico la validacion de las fechas

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