source: sipes/0.3-modules/proyectos_operativos_mcti/proyectos_operativos_mcti.module @ 98519d3

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

se agregaron los campos en la parte de busqueda de información

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