<?php
// $Id: libraries.module,v 1.2.2.3 2011/01/27 02:25:40 sun Exp $

/**
 * @file
 * External library handling for Drupal modules.
 */

/**
 * Gets the path of a library.
 *
 * @param $name
 *   The machine name of a library to return the path for.
 * @param $base_path
 *   Whether to prefix the resulting path with base_path().
 *
 * @return
 *   The path to the specified library.
 *
 * @ingroup libraries
 */
function libraries_get_path($name, $base_path = FALSE) {
  static $libraries;

  if (!isset($libraries)) {
    $libraries = libraries_get_libraries();
  }

  $path = ($base_path ? base_path() : '');
  if (!isset($libraries[$name])) {
    // Most often, external libraries can be shared across multiple sites, so
    // we return sites/all/libraries as the default path.
    $path .= 'sites/all/libraries/' . $name;
  }
  else {
    $path .= $libraries[$name];
  }

  return $path;
}

/**
 * Returns an array of library directories.
 *
 * Returns an array of library directories from the all-sites directory
 * (i.e. sites/all/libraries/), the profiles directory, and site-specific
 * directory (i.e. sites/somesite/libraries/). The returned array will be keyed
 * by the library name. Site-specific libraries are prioritized over libraries
 * in the default directories. That is, if a library with the same name appears
 * in both the site-wide directory and site-specific directory, only the
 * site-specific version will be listed.
 *
 * @return
 *   A list of library directories.
 *
 * @ingroup libraries
 */
function libraries_get_libraries() {
  global $profile;

  // When this function is called during Drupal's initial installation process,
  // the name of the profile that is about to be installed is stored in the
  // global $profile variable. At all other times, the regular system variable
  // contains the name of the current profile, and we can call variable_get()
  // to determine the profile.
  if (!isset($profile)) {
    $profile = variable_get('install_profile', 'default');
  }

  $directory = 'libraries';
  $searchdir = array();
  $config = conf_path();

  // Similar to 'modules' and 'themes' directories in the root directory,
  // certain distributions may want to place libraries into a 'libraries'
  // directory in Drupal's root directory.
  $searchdir[] = $directory;

  // The 'profiles' directory contains pristine collections of modules and
  // themes as organized by a distribution.  It is pristine in the same way
  // that /modules is pristine for core; users should avoid changing anything
  // there in favor of sites/all or sites/<domain> directories.
  if (file_exists("profiles/$profile/$directory")) {
    $searchdir[] = "profiles/$profile/$directory";
  }

  // Always search sites/all/*.
  $searchdir[] = 'sites/all/' . $directory;

  // Also search sites/<domain>/*.
  if (file_exists("$config/$directory")) {
    $searchdir[] = "$config/$directory";
  }

  // Retrieve list of directories.
  // @todo Core: Allow to scan for directories.
  $directories = array();
  $nomask = array('CVS');
  foreach ($searchdir as $dir) {
    if (is_dir($dir) && $handle = opendir($dir)) {
      while (FALSE !== ($file = readdir($handle))) {
        if (!in_array($file, $nomask) && $file[0] != '.') {
          if (is_dir("$dir/$file")) {
            $directories[$file] = "$dir/$file";
          }
        }
      }
      closedir($handle);
    }
  }

  return $directories;
}



/*graficas*/

function fusioncharts_example2___() {
  $info->data = array(
                  array('Cat', 3),
                  array('Dog', 10),
     		      array('Mouse', 4),
	          );
  $info->chart_type = 'Pie 2D';
  $info->settings = array('Caption' => 'Sample chart using the API and sample data');
  $info->attributes = array('callback' => 'example2',
                      'color' => array('121212', 'ff0000'), //no # in front of color
                      'trendline' => array(
                                      'startvalue' => 5,
                                      'displayvalue' => 'Test',
                                      'color' => '0000ff'
                                     )
                      ); 
  $info->width = 500;
  $info->height = 300;
  return theme('fusionchart', $info);
}


function fusioncharts_example2($ancho, $alto) {

		$query = "SELECT  SUM(CASE WHEN  e.EvaluacionCosto <= 3 or e.EvaluacionCosto IS NULL THEN 1 ELSE 0 END) as red_count,
                      SUM(CASE WHEN  e.EvaluacionCosto > 3 AND e.EvaluacionCosto <= 7 THEN 1 ELSE 0 END) as yellow_count,
                      SUM(CASE WHEN  e.EvaluacionCosto > 7 THEN 1 ELSE 0 END) as green_count,
                      SUM(CASE WHEN  e.EvaluacionCosto <= 3 THEN Actual ELSE 0 END) as red_amount,
                      SUM(CASE WHEN  e.EvaluacionCosto > 3 AND e.EvaluacionCosto <= 7 THEN Actual ELSE 0 END) as yellow_amount,
                      SUM(CASE WHEN  e.EvaluacionCosto > 7 THEN Actual ELSE 0 END) as green_amount
              FROM presupuestos d LEFT JOIN (SELECT IdPrograma, max(EvaluacionCosto) as EvaluacionCosto
              FROM evaluaciones tmp WHERE tmp.Fecha = (SELECT max(Fecha) FROM evaluaciones tmp2 
              WHERE tmp.IdPrograma = tmp2.IdPrograma) group by IdPrograma) e ON e.IdPrograma = d.IdPrograma 
              WHERE Periodo = ".date('Y');
	
	$res = mysql_query($query);
	    while ($row=mysql_fetch_array($res)){
			$red_count = $row['red_count'];
			$yellow_count = $row['yellow_count'];
			$green_count = $row['green_count'];
			$red_amount = $row['red_amount'];
			$yellow_amount = $row['yellow_amount'];
			$green_amount = $row['green_amount'];
		}
			  
			  
			$info->data = array(
                  array($red_count.' programas', $red_count),
                  array($yellow_count.' programas', $yellow_count),
     		      array($green_count.' programas', $green_count),
	          );
			  
			/*$info->attributes['link'] = array(
                   $red_count.' programas' => 'http://drupal.org',
                   $yellow_count.' programas' => 'http://yahoo.com',
                   $green_count.' programas' => 'http://google.com'
              );*/

		$info->chart_type = 'Pie 3D';
		$info->settings = array('Caption' => 'Evaluacion general');
		$info->attributes = array('color' => array('FF0015', 'FFE900', '158C00'), 'link' => array('http://drupal.org','http://yahoo.com','http://google.com'));
		$info->width = $ancho;
		$info->height = $alto;
		
		 return theme('fusionchart', $info);

}


/* nueva funcion de graficos */

function pie3D($numero=0, $nombres="", $valores="", $enlaces="", $color="", $ancho="", $alto="", $nombre="pie3d") {

	if ($numero != "0") {

	   $strXML  = "<graph caption='Sales by Product Category' subCaption='For this week' showPercentValues='1' pieSliceDepth='25' showNames='1' decimalPrecision='0' >";

		$nombres = explode(",",$nombres);
		$valores = explode(",",$valores);
		$enlaces = explode(",",$enlaces);
		$color = explode(",",$color);

		for ($i = 0; $i <= $numero-1; $i++) {
			 $strXML .= "<set name='" . $nombres[$i] . "' value='" . $valores[$i] . "' link='" . $enlaces[$i] . "' color='" . $color[$i] . "' />";
		}

	   $strXML .= "</graph>";

		return renderChart("modulos/fusionchart/Charts/FCF_Pie3D.swf", "", $strXML, $nombre, $ancho, $alto);

	} else {

		return "Sin datos";

	}

}

/*----------------------------------------------------- GRAFICAS INICIO --------------------------------------------------------------*/

	function departamento_inicio() {
	
	/*setlocale(LC_MONETARY, 'es_ES');
	money_format('%.2n', $row_categ['Gasto'])*/
	
		$query = "SELECT D.IdDepartamento, D.Nombre AS Departamento, D.Abrev, G.Gasto, G.Programas, EV.Evaluacion FROM departamentos D LEFT JOIN (SELECT P.IdDepartamento, SUM(B.Actual) Gasto, COUNT(P.IdPrograma) Programas FROM programas P INNER JOIN presupuestos B ON P.IdPrograma = B.IdPrograma AND B.Periodo = ".date(Y)." GROUP BY IdDepartamento) G ON D.IdDepartamento = G.IdDepartamento LEFT JOIN (SELECT P.IdDepartamento, AVG(E.EvaluacionGeneral) AS Evaluacion FROM programas P LEFT JOIN evaluaciones E ON P.IdPrograma = E.IdPrograma WHERE P.Periodo = ".date(Y)." GROUP BY P.IdDepartamento) EV ON D.IdDepartamento = EV.IdDepartamento ORDER BY D.Orden";
		
		$strXML  = "<graph numDivLines ='0' divLineColor='17375E' divLineAlpha='100' divLineThickness='0' chartLeftMargin='1' chartTopMargin='40' yAxisMaxValue='35' basefontSize='10' decimals='2' use3DLighting='0' placeValuesInside='0' yAxisName='' xAxisName='' showValues='0' shownames='1' canvasBaseDepth='0' rotateNames='1' rotateLabels='1' showLabels='1' showYAxisValues='0' toolTipBgColor='000000' baseFontColor ='000000' baseFontSize='12' borderColor='FFFFFF' canvasBorderColor='FFFFFF' canvasBorderThickness='0' canvasBgColor='17375E' canvasBgAlpha ='0' bgColor='17375E' bgAlpha='0' showLegend='0' showBorder='0' showCanvasBg='0' showPlotBorder='1' plotFillAlpha='85' plotBorderColor='414141' plotBorderAlpha='25' plotBorderThickness='0.5' showToolTip ='1' canvasBorderAlpha ='0' formatNumberScale ='0' animation='1' showFCMenuItem='0' rotateNames='1' showLimits='0' showDivLineValue='0' hoverCapSepChar=':' hoverCapBgColor='FFFFFF' numberPrefix='' numberSuffix='' >";
		
		
		$res2 = mysql_query($query);
		$xml_categ ="";
		while ($row_categ=mysql_fetch_array($res2)){
			$xml_categ .="<category name='".$row_categ['Abrev']."' label='".$row_categ['Abrev']."' hovertext='Presupuesto (".date('Y').")&#10;Numero de Programas: ".$row_categ['Programas']."&#10;Evaluacion: ".round($row_categ['Evaluacion'], 2)."&#10;Total en Euros' />";
		}
			
		$res_normal = mysql_query($query);
		$xml_datos ="";
		while ($row=mysql_fetch_array($res_normal)){
			$xml_datos .= "<set value='".round($row['Gasto'],2)."' name='".$row['Departamento']."' showName='1' color='345F94,284A73' link='cartera?depto=".$row['IdDepartamento']."' />";
		}
		
		$strXML .= "<categories>";
		$strXML .= $xml_categ;
		$strXML .= "</categories>";
			
		$strXML .="<dataset>";
		$strXML .= $xml_datos;
		$strXML .="</dataset>";
		
		
		$strXML .= "<styles><definition><style name='myHTMLFont' type='font' font='Lucida Sans Unicode' size='14' color='FFFFFF' /></definition><definition><style name='myHTMLFont10' type='font' font='Lucida Sans Unicode' size='14' color='FFFFFF' /><style name='myHTMLFont11' type='font' font='Lucida Sans Unicode' size='9' color='FFFFFF' /> <style name='myHTMLFont12' type='font' font='Lucida Sans Unicode' bold='1' size='11' color='000000' /></definition><application> <apply toObject='TOOLTIP' styles='myHTMLFont' /></application><application><apply toObject='DATAVALUES' styles='myHTMLFont12' /></application> <application><apply toObject='YAXISVALUES' styles='myHTMLFont11' /></application><application><apply toObject='DATALABELS' styles='myHTMLFont12' /> </application></styles>";
		
		
		$strXML .= "</graph>";
		
		return renderChart("modulos/fusionchart/Charts/FCF_MSColumn2D.swf", "", $strXML, "areaID", "500", "260");
	
	}


/*----------------------------------------------------- GRAFICAS CARTERA --------------------------------------------------------------*/

	function evaluacion_general($depto="", $url="") {
	
	
	//depto=11,&ente=3
	$verurl = explode(",&",$url);
	$departamento = str_replace("q=cartera&","",$verurl[0]);
	$ente = $verurl[1];

	
	//return $departamento."<br>".$ente;
	
		/*$query = "SELECT  SUM(CASE WHEN  e.EvaluacionCosto <= 3 or e.EvaluacionCosto IS NULL THEN 1 ELSE 0 END) as red_count,
                      SUM(CASE WHEN  e.EvaluacionCosto > 3 AND e.EvaluacionCosto <= 7 THEN 1 ELSE 0 END) as yellow_count,
                      SUM(CASE WHEN  e.EvaluacionCosto > 7 THEN 1 ELSE 0 END) as green_count,
                      SUM(CASE WHEN  e.EvaluacionCosto <= 3 THEN Actual ELSE 0 END) as red_amount,
                      SUM(CASE WHEN  e.EvaluacionCosto > 3 AND e.EvaluacionCosto <= 7 THEN Actual ELSE 0 END) as yellow_amount,
                      SUM(CASE WHEN  e.EvaluacionCosto > 7 THEN Actual ELSE 0 END) as green_amount FROM presupuestos d LEFT JOIN (SELECT IdPrograma, max(EvaluacionCosto) as EvaluacionCosto FROM evaluaciones tmp WHERE tmp.Fecha = (SELECT max(Fecha) FROM evaluaciones tmp2 WHERE tmp.IdPrograma = tmp2.IdPrograma) group by IdPrograma) e ON e.IdPrograma = d.IdPrograma WHERE Periodo = ".date('Y');*/
		
			
		$url = str_replace("e_gene=R","",$url);
		$url = str_replace("e_gene=A","",$url);
		$url = str_replace("e_gene=V","",$url);
		
		if ($depto) {
		
		$query="SELECT Fecha, EXTRACT(MONTH FROM Fecha) AS month_value, EXTRACT(YEAR FROM Fecha) AS year_value,
		SUM(CASE WHEN EvaluacionGeneral <=3 THEN 1 ELSE 0 END) AS red_count,
		SUM(CASE WHEN EvaluacionGeneral >3 AND EvaluacionGeneral <7 THEN 1 ELSE 0 END) AS yellow_count,
		SUM(CASE WHEN EvaluacionGeneral >=7 THEN 1 ELSE 0 END) AS green_count,
		(CASE WHEN SUM(CASE WHEN EvaluacionGeneral <=3 THEN 1 ELSE 0 END) = 0 THEN 0 
		ELSE SUM(CASE WHEN EvaluacionGeneral <=3 THEN EvaluacionGeneral ELSE 0 END)/SUM(CASE WHEN EvaluacionGeneral <=3 THEN 1 ELSE 0 END) END) AS red_rating,
		(CASE WHEN SUM(CASE WHEN EvaluacionGeneral >3 AND EvaluacionGeneral <7 THEN 1 ELSE 0 END) = 0 THEN 0 
		ELSE SUM(CASE WHEN EvaluacionGeneral >3 AND EvaluacionGeneral <7 THEN EvaluacionGeneral ELSE 0 END)/SUM(CASE WHEN EvaluacionGeneral >3 AND EvaluacionGeneral <7 THEN 1 ELSE 0 END) END) AS yellow_rating,
		(CASE WHEN SUM(CASE WHEN EvaluacionGeneral >=7 THEN 1 ELSE 0 END) = 0 THEN 0 
		ELSE SUM(CASE WHEN EvaluacionGeneral >=7 THEN EvaluacionGeneral ELSE 0 END)/SUM(CASE WHEN EvaluacionGeneral >=7 THEN 1 ELSE 0 END) END) AS green_rating, 
		SUM(CASE WHEN EvaluacionGeneral <=3 THEN Actual ELSE 0 END) AS red_amount, 
		SUM(CASE WHEN EvaluacionGeneral >3 AND EvaluacionGeneral <7 THEN Actual ELSE 0 END) AS yellow_amount, 
		SUM(CASE WHEN EvaluacionGeneral >=7 THEN Actual ELSE 0 END) AS green_amount 
		FROM programas P, presupuestos R, evaluaciones E WHERE P.IdPrograma = R.IdPrograma AND R.IdPrograma = E.IdPrograma ";
		
		
			if ($departamento) {
				$IDdepartamento = explode("=",$departamento);
				if ($IDdepartamento[1] != "cartera") {
					$query .= "AND P.IdDepartamento = $IDdepartamento[1] ";
				}
			}
			
			if ($ente) {
				$IDente = explode("=",$ente);
				$query .= "AND P.IdEntidad = $IDente[1] ";
			}
		
		$query .= "AND datediff(date(Fecha), date_sub(str_to_date(concat('01,',extract(month from curdate()),',',extract(year from curdate())),'%d,%m,%Y'),INTERVAL 6 MONTH)) >=0 AND R.Periodo = ".date('Y')." 
		GROUP BY 1,2,3 ORDER BY 1";
		
		
			//return $query ;
			
			/*$res2 = mysql_query($query);
			$xml_fecha ="";
			while ($row_fecha=mysql_fetch_array($res2)){
				$xml_fecha .="<category label='".$row_fecha['Fecha']."' />";
			}
			
			$res_normal = mysql_query($query);
			$xml_evaplan ="";
			while ($row=mysql_fetch_array($res_normal)){
				$xml_evaplan .="<set value='".round($row['red_rating'],0)."' />";
			}
			
			$res_aten = mysql_query($query);
			$xml_atencion ="";
			while ($row=mysql_fetch_array($res_aten)){
				$xml_atencion .="<set value='".round($row['yellow_rating'],0)."' />";
			}
			
			$res_riesgos = mysql_query($query);
			$xml_riesgos ="";
			while ($row=mysql_fetch_array($res_riesgos)){
				$xml_riesgos .="<set value='".round($row['green_rating'],0)."' />";
			}*/
			
			 $res2 = db_query($query);
				  $xml_fecha ="";
				  $xml_evaplan ="";
				  $xml_atencion ="";
				  $xml_riesgos ="";
			   while ($row_fecha=db_fetch_object($res2)){
					$xml_fecha .="<category label='".$row_fecha->Fecha."' />";
					$xml_evaplan .="<set value='".round($row->red_rating,0)."' />";
					$xml_atencion .="<set value='".round($row->yellow_rating,0)."' />";
					$xml_riesgos .="<set value='".round($row->green_rating,0)."' />";
			   }
			
			
			$strXML  = "<graph showCanvasBg='0' showBorder='0' showLegend='0' numDivLines='0' bgColor='FFFFFF' YAxisName='Programas Evaluados' XAxisName='Evolucion en el Tiempo' SYAxisName='Overall Rating' drawAnchors='1' anchorSides='3' anchorAlpha='0' anchorRadius='20' anchorBorderColor='000000' canvasBgColor='FFFFFF' showValues='0' canvasBorderColor ='FFFFFF' canvasBorderThickness='0' plotFillAngle='360' plotFillAlpha='100' plotBorderThickness='0' plotBorderAlpha='0' plotGradientColor='' yAxisMinValue ='1' yAxisMaxValue ='10' showTooltip='0' yAxisValuesStep='0' legendBorderColor='FFFFFF' legendShadow='0' chartRightMargin='25' showLabels='1' labelStep='5' labelDisplay='WRAP'>";
			
			
			$strXML .= "<categories>";
			$strXML .= $xml_fecha;
			$strXML .= "</categories>";
			
			$strXML .="<dataset seriesName='Normal' color='5C9E16' renderAs='Area' parentYAxis='P' areaAlpha='50' >";
			$strXML .= $xml_evaplan;
			$strXML .="</dataset>";
			
			$strXML .="<dataset seriesName='Necesita_Atencion' color='FFD205' renderAs='Area' parentYAxis='P' areaAlpha='50' >";
			$strXML .= $xml_atencion;
			$strXML .="</dataset>";
			
			$strXML .="<dataset seriesName='Riegos_Considerables' color='CD4343' renderAs='Area' parentYAxis='P' areaAlpha='50' >";
			$strXML .= $xml_riesgos;
			$strXML .="</dataset>";
			
			
			/*$strXML .= "<styles><definition><style name='myFont' type='font' isHTML='1' bold='1' size='9' color='6196B8' /></definition><application><apply toObject='YAxisValues' styles='myFont' /><apply toObject='DataLabels' styles='myFont' /><apply toObject='DataValues' styles='myFont' /><apply toObject='Caption' styles='myFont' /></application></styles>";*/
			
			$strXML .= "</graph>";
			
			
			return renderChart("modulos/fusionchart/Charts/FCF_MSArea2D.swf?ChartNoDataText=No Hay Datos", "", $strXML, "grafica10", "350", "150");
			  
			  
		} else {
		
		$query="SELECT SUM(CASE WHEN  E.EvaluacionGeneral <= 3 OR E.EvaluacionGeneral IS NULL THEN 1 ELSE 0 END) AS red_count,
               SUM(CASE WHEN  E.EvaluacionGeneral > 3 AND E.EvaluacionGeneral <=7 THEN 1 ELSE 0 END) AS yellow_count,
               SUM(CASE WHEN  E.EvaluacionGeneral > 7 THEN 1 ELSE 0 END) AS green_count,
               SUM(CASE WHEN  E.EvaluacionGeneral <= 3 or E.EvaluacionGeneral IS NULL THEN Actual ELSE 0 END) AS red_amount,
               SUM(CASE WHEN  E.EvaluacionGeneral > 3 AND E.EvaluacionGeneral <=7 THEN Actual ELSE 0 END) AS yellow_amount,
               SUM(CASE WHEN  E.EvaluacionGeneral > 7 THEN Actual ELSE 0 END) AS green_amount FROM presupuestos R LEFT JOIN (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E ON R.IdPrograma = E.IdPrograma WHERE R.Periodo = ".date('Y');
			   
			$res = mysql_query($query);
			while ($row=mysql_fetch_array($res)){
				$red_count = $row['red_count'];
				$yellow_count = $row['yellow_count'];
				$green_count = $row['green_count'];
				$red_amount = $row['red_amount'];
				$yellow_amount = $row['yellow_amount'];
				$green_amount = $row['green_amount'];
			}
			
			   
			$strXML  = "<graph chartLeftMargin='1' chartRightMargin='1' chartTopMargin='1' chartBottomMargin='1' caption='' xAxisName='' showhovercap='1' shownames='0' showValues='0' decimals='0' decimalPrecision='2' formatNumberScale='0' labelDisplay='rotate' bgColor='FFFFFF' showBorder='0' borderColor=''  toolTipBgColor='000000'  baseFontColor='003366' baseFontSize='11' borderAlpha='100' showValue='0' showToolTip='1' showLabels='1'  slantLabels='1' use3DLighting='0' showShadow='0' animation='0' slicingDistance='0' showPlotBorder='0'  pieYScale='60' pieRadius='100'  >";
			
			$strXML .= "<set name='".$red_count." programas' value='" . $red_count . "' link='cartera?e_gene=R&".$url."' color='#D1513C' />";
			  $strXML .= "<set name='".$yellow_count." programas' value='" . $yellow_count . "' link='cartera?e_gene=A&".$url."' color='#F0CD08' />";
			  $strXML .= "<set name='".$green_count." programas' value='" . $green_count . "' link='cartera?e_gene=V&".$url."' color='#6CA72D' />";
			  
			  
			 $strXML .= "</graph>";
			 
			 
			return renderChart("modulos/fusionchart/Charts/FCF_Pie3D.swf?ChartNoDataText=No Hay Datos", "", $strXML, "grafica1", "350", "182");
			  
		}

		
	
	}
	
	
	function histiorial_evaluaciones($url="") {
	
	$verurl = explode(",&",$url);
	$departamento = str_replace("q=cartera&","",$verurl[0]);
	$ente = $verurl[1];
	
		 $query="SELECT Fecha, AVG(EvaluacionResponsable * 2) AS EvaluacionResponsable, AVG(EvaluacionPlan) AS EvaluacionPlan, AVG(EvaluacionCosto) AS EvaluacionCosto, extract(month FROM Fecha) AS month_value,extract(year FROM Fecha) AS year_value, AVG(EvaluacionGeneral) AS EvaluacionGeneral FROM programas P, presupuestos R LEFT JOIN evaluaciones E on R.IdPrograma = E.IdPrograma AND R.Periodo = ".date('Y')." WHERE Fecha IS NOT NULL ";
		 
		if ($departamento) {	
			$IDdepartamento = explode("=",$departamento);
			if ($IDdepartamento[1] != "cartera") {
				$query .= "AND P.IdDepartamento = $IDdepartamento[1] ";
			}
		}
			
		if ($ente) {
			$IDente = explode("=",$ente);
			$query .= "AND P.IdEntidad = $IDente[1] ";
		}
		 
		 
		 $query .= "GROUP BY 1 ORDER BY 1";
		 
		 
			$res = mysql_query($query);
			$xml_evarespon ="";
			while ($row=mysql_fetch_array($res)){
				$xml_evarespon .="<set value='".round($row['EvaluacionResponsable'],2)."' />";
			}
			
			$res_plan = mysql_query($query);
			$xml_evaplan ="";
			while ($row=mysql_fetch_array($res_plan)){
				$xml_evaplan .="<set value='".round($row['EvaluacionPlan'],2)."' />";
			}
			
			$res_costo = mysql_query($query);
			$xml_evacosto ="";
			while ($row=mysql_fetch_array($res_costo)){
				$xml_evacosto .="<set value='".round($row['EvaluacionCosto'],2)."' />";
			}
			
			
			
			$res2 = mysql_query($query);
			$xml_fecha ="";
			while ($row_fecha=mysql_fetch_array($res2)){
				$xml_fecha .="<category label='".$row_fecha['year_value']." ".$row_fecha['month_value']."' />";
			}
		 
	
	$strXML ="<graph  showBorder='0'  bgColor='FFFFFF' showLegend='0' yAxisName='Evaluacion' drawAnchors='0' anchorSides='0' anchorAlpha='100' anchorRadius='5' anchorBorderColor='000000' canvasBgColor='FFFFFF' showValues='0' canvasBorderColor='CED4D8' canvasBorderThickness='0' plotFillAngle='360'  plotFillAlpha='100'  plotBorderThickness='' plotBorderAlpha='0' plotGradientColor='' showTooltip='1' showDivLineValues='1' showShadow='0' yAxisMinValue='0' yAxisMaxValue='10'  yAxisValuesStep='1' showAlternateHGridColor='1' numDivLines='1'  showLabels='1'  labelStep='13' xAxisName='' rotateNames='1' decimalPrecision='0' labelDisplay='WRAP'>";
	
	/*$strXML .= "<set name='".$EvaluacionPlan." programas' value='" . $EvaluacionPlan . "' link='cartera?e_respon=R' color='#D1513C' />";
			  $strXML .= "<set name='".$EvaluacionCosto." programas' value='" . $EvaluacionCosto . "' link='cartera?e_respon=A' color='#F0CD08' />";
			  $strXML .= "<set name='".$EvaluacionGeneral." programas' value='" . $EvaluacionGeneral . "' link='cartera?e_respon=V' color='#6CA72D' />";*/
	
	$strXML .= "<categories>";
	$strXML .= $xml_fecha;
	$strXML .= "</categories>";
	
	$strXML .="<dataset seriesName='EvaluacionResponsable' color='#016CB5' >";
	$strXML .= $xml_evarespon;
	$strXML .="</dataset>";
	
	$strXML .="<dataset seriesName='EvaluacionCosto' color='#B1B4B6' >";
	$strXML .= $xml_evacosto;
	$strXML .="</dataset>";
	
	$strXML .="<dataset seriesName='EvaluacionPlan' color='#02385D' >";
	$strXML .= $xml_evaplan;
	$strXML .="</dataset>";
	

	$strXML .= "<styles><definition><style name='myFont' type='font' isHTML='1' bold='1' size='9' color='6196B8' /></definition><application><apply toObject='YAxisValues' styles='myFont' /><apply toObject='XAxisValues' styles='myFont' /><apply toObject='DataLabels' styles='myFont' /><apply toObject='DataValues' styles='myFont' /><apply toObject='Caption' styles='myFont' /></application></styles>";
	
	$strXML .= "</graph>";

		return renderChart("modulos/fusionchart/Charts/FCF_MSLine.swf", "", $strXML, "grafica5", "280", "170");
	
	
	
	
	}
	
	function evaluacion_responsable($colorconfig="FFFFFF",$url="") {
	
	$verurl = explode(",&",$url);
	$departamento = str_replace("q=cartera&","",$verurl[0]);
	$ente = $verurl[1];
	
	$query = "SELECT SUM(CASE WHEN E.EvaluacionResponsable <= 2 OR E.EvaluacionResponsable IS NULL THEN 1 ELSE 0 END) AS red_count,
				 SUM(CASE WHEN E.EvaluacionResponsable > 2 AND E.EvaluacionResponsable <= 3.5 THEN 1 ELSE 0 END) AS yellow_count,
                 SUM(CASE WHEN E.EvaluacionResponsable > 3.5 THEN 1 ELSE 0 END) AS green_count,
                 SUM(CASE WHEN E.EvaluacionResponsable <= 2 OR E.EvaluacionResponsable IS NULL THEN Actual ELSE 0 END) AS red_amount,
                 SUM(CASE WHEN E.EvaluacionResponsable > 2 AND E.EvaluacionResponsable <= 3.5 THEN Actual ELSE 0 END) AS yellow_amount,
                 SUM(CASE WHEN E.EvaluacionResponsable > 3.5 THEN Actual ELSE 0 END) AS green_amount FROM programas P, presupuestos R LEFT JOIN (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E ON R.IdPrograma = E.IdPrograma WHERE R.Periodo = ".date('Y');
				 
		if ($departamento) {
			$IDdepartamento = explode("=",$departamento);
			if ($IDdepartamento[1] != "cartera") {
				$query .= " AND P.IdDepartamento = $IDdepartamento[1] ";
			}
		}
			
		if ($ente) {
			$IDente = explode("=",$ente);
			$query .= " AND P.IdEntidad = $IDente[1] ";
		}
				 
				 
				 $res = mysql_query($query);
			while ($row=mysql_fetch_array($res)){
				$red_count = $row['red_count'];
				$yellow_count = $row['yellow_count'];
				$green_count = $row['green_count'];
				$red_amount = $row['red_amount'];
				$yellow_amount = $row['yellow_amount'];
				$green_amount = $row['green_amount'];
			}
			
			
		$strXML  = "<graph chartLeftMargin='1' chartRightMargin='1' chartTopMargin='1' chartBottomMargin='1' caption='' xAxisName='' showhovercap='0' shownames='0' showValues='0' decimals='0' decimalPrecision='2' formatNumberScale='0' labelDisplay='rotate' bgColor='".$colorconfig."' showBorder='0' borderColor=''  toolTipBgColor='000000'  baseFontColor='003366' baseFontSize='11' borderAlpha='100' showValue='0' showToolTip='0' showLabels='0'  slantLabels='1' use3DLighting='0' showShadow='0' animation='0' slicingDistance='0' showPlotBorder='0'  >";

			 $strXML .= "<set name='".$red_count." programas' value='" . $red_count . "' link='cartera?e_respon=R' color='#D1513C' />";
			  $strXML .= "<set name='".$yellow_count." programas' value='" . $yellow_count . "' link='cartera?e_respon=A' color='#F0CD08' />";
			  $strXML .= "<set name='".$green_count." programas' value='" . $green_count . "' link='cartera?e_respon=V' color='#6CA72D' />";


	   $strXML .= "</graph>";

		return renderChart("modulos/fusionchart/Charts/FCF_Pie2D.swf", "", $strXML, "grafica2", "40", "40");
	
	
	}
	
	
	
	function costo($colorconfig="FFFFFF",$url="") {
	
	$verurl = explode(",&",$url);
	$departamento = str_replace("q=cartera&","",$verurl[0]);
	$ente = $verurl[1];
	
	$query = "SELECT SUM(CASE WHEN E.EvaluacionCosto <= 3 OR E.EvaluacionCosto IS NULL THEN 1 ELSE 0 END) AS red_count,
                 SUM(CASE WHEN E.EvaluacionCosto > 3 AND E.EvaluacionCosto <= 7 THEN 1 ELSE 0 END) AS yellow_count,
                 SUM(CASE WHEN E.EvaluacionCosto > 7 THEN 1 ELSE 0 END) AS green_count,
                 SUM(CASE WHEN E.EvaluacionCosto <= 3 THEN Actual ELSE 0 END) AS red_amount,
                 SUM(CASE WHEN E.EvaluacionCosto > 3 AND E.EvaluacionCosto <= 7 THEN Actual ELSE 0 END) AS yellow_amount,
                 SUM(CASE WHEN E.EvaluacionCosto > 7 THEN Actual ELSE 0 END) AS green_amount FROM programas P, presupuestos R LEFT JOIN (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E ON R.IdPrograma = E.IdPrograma WHERE R.Periodo = ".date('Y');
	
		if ($departamento) {
			$IDdepartamento = explode("=",$departamento);
			if ($IDdepartamento[1] != "cartera") {
				$query .= " AND P.IdDepartamento = $IDdepartamento[1] ";
			}
		}
			
		if ($ente) {
			$IDente = explode("=",$ente);
			$query .= " AND P.IdEntidad = $IDente[1] ";
		}
		
				 
				 $res = mysql_query($query);
			while ($row=mysql_fetch_array($res)){
				$red_count = $row['red_count'];
				$yellow_count = $row['yellow_count'];
				$green_count = $row['green_count'];
				$red_amount = $row['red_amount'];
				$yellow_amount = $row['yellow_amount'];
				$green_amount = $row['green_amount'];
			}
			
			
		$strXML  = "<graph chartLeftMargin='1' chartRightMargin='1' chartTopMargin='1' chartBottomMargin='1' caption='' xAxisName='' showhovercap='0' shownames='0' showValues='0' decimals='0' decimalPrecision='2' formatNumberScale='0' labelDisplay='rotate' bgColor='".$colorconfig."' showBorder='0' borderColor=''  toolTipBgColor='000000'  baseFontColor='003366' baseFontSize='11' borderAlpha='100' showValue='0' showToolTip='0' showLabels='0'  slantLabels='1' use3DLighting='0' showShadow='0' animation='0' slicingDistance='0' showPlotBorder='0'  >";

			$strXML .= "<set name='".$red_count." programas' value='" . $red_count . "' link='cartera?e_costo=R' color='#D1513C' />";
			  $strXML .= "<set name='".$yellow_count." programas' value='" . $yellow_count . "' link='cartera?e_costo=A' color='#F0CD08' />";
			  $strXML .= "<set name='".$green_count." programas' value='" . $green_count . "' link='cartera?e_costo=V' color='#6CA72D' />";


	   $strXML .= "</graph>";

		return renderChart("modulos/fusionchart/Charts/FCF_Pie2D.swf", "", $strXML, "grafica3", "40", "40");
	
	
	}
	
	
	function plan($colorconfig="FFFFFF",$url="") {
	
	$query = "SELECT SUM(CASE WHEN E.EvaluacionPlan > 7 THEN 1 ELSE 0 END) AS green_count,
                 SUM(CASE WHEN E.EvaluacionPlan > 3 AND E.EvaluacionPlan <= 7 THEN 1 ELSE 0 END) AS yellow_count,
                 SUM(CASE WHEN E.EvaluacionPlan <= 3 OR E.EvaluacionPlan IS NULL THEN 1 ELSE 0 END) AS red_count,
                 SUM(CASE WHEN E.EvaluacionPlan > 7 THEN Actual ELSE 0 END) AS green_amount,
                 SUM(CASE WHEN E.EvaluacionPlan > 3 AND E.EvaluacionPlan <= 7 THEN Actual ELSE 0 END) AS yellow_amount,
                 SUM(CASE WHEN E.EvaluacionPlan <= 3 THEN Actual ELSE 0 END) AS red_amount FROM programas P, presupuestos R LEFT JOIN (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E ON R.IdPrograma = E.IdPrograma WHERE R.Periodo = ".date('Y');
				 
		if ($departamento) {
			$IDdepartamento = explode("=",$departamento);
			if ($IDdepartamento[1] != "cartera") {
				$query .= " AND P.IdDepartamento = $IDdepartamento[1] ";
			}
		}
			
		if ($ente) {
			$IDente = explode("=",$ente);
			$query .= " AND P.IdEntidad = $IDente[1] ";
		}
				 
				 
				 $res = mysql_query($query);
			while ($row=mysql_fetch_array($res)){
				$red_count = $row['red_count'];
				$yellow_count = $row['yellow_count'];
				$green_count = $row['green_count'];
				$red_amount = $row['red_amount'];
				$yellow_amount = $row['yellow_amount'];
				$green_amount = $row['green_amount'];
			}
			
			
		$strXML  = "<graph chartLeftMargin='1' chartRightMargin='1' chartTopMargin='1' chartBottomMargin='1' caption='' xAxisName='' showhovercap='0' shownames='0' showValues='0' decimals='0' decimalPrecision='2' formatNumberScale='0' labelDisplay='rotate' bgColor='".$colorconfig."' showBorder='0' borderColor=''  toolTipBgColor='000000'  baseFontColor='003366' baseFontSize='11' borderAlpha='100' showValue='0' showToolTip='0' showLabels='0'  slantLabels='1' use3DLighting='0' showShadow='0' animation='0' slicingDistance='0' showPlotBorder='0'  >";

			$strXML .= "<set name='".$red_count." programas' value='" . $red_count . "' link='cartera?e_plan=R' color='#D1513C' />";
			  $strXML .= "<set name='".$yellow_count." programas' value='" . $yellow_count . "' link='cartera?e_plan=A' color='#F0CD08' />";
			  $strXML .= "<set name='".$green_count." programas' value='" . $green_count . "' link='cartera?e_plan=V' color='#6CA72D' />";


	   $strXML .= "</graph>";

		return renderChart("modulos/fusionchart/Charts/FCF_Pie2D.swf", "", $strXML, "grafica4", "40", "40");
	
	
	}

/*----------------------------------------------------- FIN GRAFICAS CARTERA --------------------------------------------------------------*/

	function variacion_costo(){
	
	
	}


/*----------------------------------------------------- FIN VARIACION DE COSTO --------------------------------------------------------------*/

	function promedio_responsable($url) {
	
	$verurl = explode(",&",$url);
	$departamento = str_replace("q=cartera&","",$verurl[0]);
	$ente = $verurl[1];
	
			$query = "";
			
			//$query .= "Select IdEntidad, IdDepartamento FROM Programas P INNER JOIN (";

			$query .= "Select AVG(CASE WHEN E.EvaluacionResponsable >= '4.5' THEN '10' 
        			WHEN E.EvaluacionResponsable >= '3.5' THEN '7.5' 
        			WHEN E.EvaluacionResponsable >= '2.5' THEN '5' 
        			WHEN E.EvaluacionResponsable >= '1.5' THEN '2.5' 
        			ELSE E.EvaluacionResponsable = '0' END) AS valor 
					FROM (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E";
			
			/*$query .= "Select AVG(CASE WHEN E.EvaluacionResponsable >= '4.5' THEN '10' 
				WHEN E.EvaluacionResponsable >= '3.5' THEN '7.5' 
				WHEN E.EvaluacionResponsable >= '2.5' THEN '5' 
				WHEN E.EvaluacionResponsable >= '1.5' THEN '2.5' 
				ELSE E.EvaluacionResponsable = '0' END) AS valor 
				FROM programas P 
				LEFT JOIN (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) 
				EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E
				WHERE P.IdPrograma = E.IdPrograma";*/
					
			/*$query .= ") E ON P.IdPrograma = E.IdPrograma";
			
			if ($departamento) {
				$IDdepartamento = explode("=",$departamento);
				if ($IDdepartamento[1] != "cartera") {
					$query .= " AND P.IdDepartamento = $IDdepartamento[1] ";
				}
			}
				
			if ($ente) {
				$IDente = explode("=",$ente);
				$query .= " AND P.IdEntidad = $IDente[1] ";
			}
				//return $query;*/
					
			$res = mysql_query($query);
			while ($row=mysql_fetch_array($res)){
				return $row['valor'];
			}
	
	}
	
	function promedio_costo() {

		$query = "Select AVG(CASE WHEN E.EvaluacionCosto IS NULL THEN 0 ELSE E.EvaluacionCosto END) AS EvaluacionCosto FROM (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E";
		
			$res = mysql_query($query);
			while ($row=mysql_fetch_array($res)){
				return $row['EvaluacionCosto'];
			}

	}
	
	function promedio_plan() {

		$query = "Select AVG(CASE WHEN E.EvaluacionPlan IS NULL THEN 0 ELSE E.EvaluacionPlan END) AS EvaluacionPlan FROM (SELECT EV.* FROM evaluaciones EV, (SELECT IdPrograma, MAX(Fecha) AS Fecha FROM evaluaciones GROUP BY IdPrograma) EV2 WHERE EV.IdPrograma = EV2.IdPrograma AND EV.Fecha = EV2.Fecha) E";
		
			$res = mysql_query($query);
			while ($row=mysql_fetch_array($res)){
				return $row['EvaluacionPlan'];
			}

	}
	
	function colorvalor($tipo, $valor) {
	
		if ($tipo == "costo") {
			if($valor <3 ){
				return "chart_Number perf_AvgNum2";
			} else if($valor >= 3 && $valor < 7){
				return "chart_Number perf_AvgNum3";
			} else if($valor >= 7){
				return "chart_Number perf_AvgNum1";
			}
		}

		if ($tipo == "plan") {
			if($valor <3){
				return "chart_Number perf_AvgNum2";
			} else if($valor >= 3 && $valor <7){
				return "chart_Number perf_AvgNum3";
			} else if($valor >= 7){
				return "chart_Number perf_AvgNum1";
			}
		}

		if ($tipo == "eval") {
			if($valor < 3){
				return "chart_Number perf_AvgNum2";
			} else if($valor >= 3 && $valor < 7){
				return "chart_Number perf_AvgNum3";
			} else if($valor >= 7){
				return "chart_Number perf_AvgNum1";
			}
		}
	
	}
