<?php
/*
 * DON'T REMOVE THE FOLLOWING LICENSE
 *           INFORMATION!
 * ----------------------------------
 * Copyright by
 * Global Cube Business Solutions
 * Author: Dennis Ritz
 * info@global-cube.de
 * 2007-2008
 * ----------------------------------
 */

class MISView extends App {
	public function __construct() {
		parent::__construct(__file__);
	}
	
	/*
	 * init
	 * ----
	 * This function sets the main workaround for this class.
	 */
	public function __init() {
		return $this->__COMPONENT();
	}
	
	public function getMain($p_view="overview",$p_sectionID = null) {
		$MISConfig = new MISConfig();
		$projectDOM = new DOMDocument('1.0', 'iso-8859-1');
		$projectDOM->load($MISConfig->getConfigFile());
		$projectXpath = new DOMXpath($projectDOM);
		
		if($this->getAuth()) {
			$p_args = func_get_args();
			array_shift($p_args);
			$view = null;
			$scorecardList = $projectXpath->query("/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID='".$p_sectionID."' and ./../../@Directory='".$this->getUsername()."\']");
			$reportList = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./../../@ID='".$p_sectionID."' and ./Directory='".$this->getUsername()."\' and ./Active='J']");
			$dashboardList = $projectXpath->query("/Configuration/Dashboards/Dashboard/Reviews/Review[./../../@Directory='".$this->getUsername()."\' and ./../../@ID='".$p_sectionID."']");
					
			if($p_view=="reports") {
				if(!$reportList->length > 0){
					if($scorecardList->length > 0)$p_view = "scorecards";
					elseif($dashboardList->length > 0)$p_view = "dashboards";
					else $p_view = "overview";
				}
			}
			if($p_view=="scorecards") {
				if(!$scorecardList->length > 0){
					if($reportList->length > 0)$p_view = "reports";
					elseif($dashboardList->length > 0)$p_view = "dashboards";
					else $p_view = "overview";
				}
			}
			if($p_view=="dashboards") {
				if(!$dashboardList->length > 0){
					if($reportList->length > 0)$p_view = "reports";
					elseif($scorecardList->length > 0)$p_view = "scorecards";
					else $p_view = "overview";
				}
			}
			
			$eval= '';
			$ret = '<div id="content">';


			switch($p_view) {
				case "overview":		$arr = call_user_func_array(array($this, $p_view), $p_args);
										$ret.= $arr[0];$eval.=implode(";",$arr[1]);
										if($this->isRole("admin")) {
											$sectionLabel = new Label(new Icon("img/configurator.png"),$this->_getI18N("configurator"));
											$eval .= ';CMgr.getMODEL().setLeftFootbar(\'<div id="sectionItem" onclick="CMgr.getMODEL().getMain(\\\'MISConfigurator\\\',\\\'info\\\');">'.$sectionLabel.'</div>\');';
										}
                                        break;
				case "reports":			$arr = call_user_func_array(array($this, $p_view), $p_args);
										$ret.= $arr[0];$eval.=implode(";",$arr[1]);
									    $sectionLabel = new Label(new Icon("img/arrow_back.png"),$this->_getI18N("back"));
                                        $eval .= ';CMgr.getMODEL().setLeftToolbar(\'<div id="sectionItem" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'overview\\\');">'.$sectionLabel.'</div>\');';
										break;
				case "scorecards":		$arr = call_user_func_array(array($this, $p_view), $p_args);
										$ret.= $arr[0];$eval.=$arr[1];
                                        $sectionLabel = new Label(new Icon("img/arrow_back.png"),$this->_getI18N("back"));
                                        $eval .= ';CMgr.getMODEL().setLeftToolbar(\'<div id="sectionItem" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'overview\\\');">'.$sectionLabel.'</div>\');';
                                        break;
									
                case "dashboards":      $arr = call_user_func_array(array($this, $p_view), $p_args);
                                        $ret.= $arr[0];$eval.=$arr[1];
                                        $sectionLabel = new Label(new Icon("img/arrow_back.png"),$this->_getI18N("back"));
                                        $eval .= ';CMgr.getMODEL().setLeftToolbar(\'<div id="sectionItem" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'overview\\\');">'.$sectionLabel.'</div>\');';
                                        break;
				default:				$ret.= $this->_getI18N("noViewAvailableInfoMsg");
										$eval.=';CMgr.getMODEL().setLocationName(\''.$p_view.'\');';break;
			}

			$ret.= '
		</div>';
			return array($ret,$eval);
		} else {
			return array('','CMgr.getMODEL().getMain();');	
		}
	}
	
	private function overview() {
		if($this->getAuth()) {
			$MISConfig = new MISConfig();
	        $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
	        $projectDOM->load($MISConfig->getConfigFile());
	        $projectXpath = new DOMXpath($projectDOM);

			$eval = array();
			
			$menu = new Tree("sectionMenu");
			$this->getSectionMenu($menu);
			array_push($eval,'CMgr.getMODEL().setNavContainer(\''.addslashes(''.$menu.'').'\')');
			array_push($eval,'Tree.setToUserView(Browser.getElementById("sectionMenu"))');
			
			$configName = $projectXpath->query("/Configuration")->item(0)->getAttribute("Name");
			$confLabel = new Label($configName);
			array_push($eval,'CMgr.getMODEL().setLocationName(\''.addslashes($confLabel).'\')');
			array_push($eval,'CMgr.getMODEL().setMainHead(\'\')');
			array_push($eval,'CMgr.getMODEL().setLeftToolbar(\'\')');
			array_push($eval,'CMgr.getMODEL().setMainToolbar(\'\')');
			
        	$tpl = $this->Template();
        	include(ROOT_DIR."apps/MISView/version.php");

        	if($projectXpath->query("/Configuration/Version")->item(0)->getAttribute("show") == "true")
            	$tpl->assign("version",$version);
        	$ret = $tpl->fetch('overview.tpl');
			
			return array($ret,$eval);
		} else {
			return array('','CMgr.getMODEL().getMain();');	
		}

	}
	
	private function getSectionMenu($p_node,$p_parentID="",$projectDOM=null,$projectXpath=null) {
		if($projectDOM == null) {
		$MISConfig = new MISConfig();
		$projectDOM = new DOMDocument('1.0', 'iso-8859-1');
		$projectDOM->load($MISConfig->getConfigFile());
		}
		if($projectXpath == null) {
		$projectXpath = new DOMXpath($projectDOM);		
		}
		$childsHaveValue = $sectionHasValue = $isVisible = false;

		$PPList = $projectXpath->query('/Configuration/Publishes/Publish[./@parentID = "'.$p_parentID.'"]');
		$Hauptampeln = $projectXpath->query('/Configuration/Publishes/Publish[./@User="'.$this->getUsername().'" and ./@Alert="true"]');
		if($Hauptampeln->length >0) $Hauptampeln = true;
		else $Hauptampeln = false;
		
		for($k=0;$k < $PPList->length;$k++) {
			$PP = $PPList->item($k);
			
			if($PP->nodeType != XML_ELEMENT_NODE) continue;
			$sectionID = $PP->getAttribute("ID");
			$sectionName = $PP->getAttribute("Name");
			$sectionHasValue = ($projectXpath->query('/Configuration/Publishes/Publish[./@ID="'.$sectionID.'" and ./Images/Image/Directory="'.$this->getUsername().'\\"]')->length > 0) ? true : false;
			$sectionHasReport = $sectionHasValue;
			if(!$sectionHasValue) $sectionHasValue = ($projectXpath->query('/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID="'.$sectionID.'" and ./../../@Directory="'.$this->getUsername().'\\"]')->length > 0) ? true : false;
			if(!$sectionHasValue) $sectionHasValue = ($projectXpath->query('/Configuration/Dashboards/Dashboard/Reviews/Review[./../../@ID="'.$sectionID.'" and ./../../@Directory="'.$this->getUsername().'\\"]')->length > 0) ? true : false;
			if(!$sectionHasReport) $sectionHasReport = ($projectXpath->query('/Configuration/Dashboards/Dashboard/Reviews/Review[./../../@ID="'.$sectionID.'" and ./../../@Directory="'.$this->getUsername().'\\"]')->length > 0) ? true : false;
			$subPPList = $projectXpath->query('/Configuration/Publishes/Publish[./@parentID = "'.$sectionID.'"]');
			

			$PPHauptampel = $projectXpath->query('/Configuration/Publishes/Publish/@Alert[./../@ID="'.$sectionID.'"]')->item(0)->nodeValue;
			if($PPHauptampel == "true") {
				$icon = new Icon("?&rc=MISView&rm=getSectionStatusImg&ras[]=".$sectionID);
                $eventListener = new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","scorecards","'.$sectionID.'");');
                $icon->addEventListener($eventListener);
			 $newLabel = new Label($icon,str_replace("_"," ",$sectionName));
			}else{
				if($Hauptampeln) $newLabel = new Label(new Icon("img/MISView/sectionStatus_blank.png"),str_replace("_"," ",$sectionName));
				else $newLabel = new Label(str_replace("_"," ",$sectionName));
			}
			$newTreeNode = new TreeNode($newLabel,"sectionMenu_".$sectionID);
			if($sectionHasReport)
			$eventListener = new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","reports","'.$sectionID.'");');
			else 
			$eventListener = new EventListener("onclick",'Tree.expand(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);');
			$newLabel->addEventListener($eventListener);
			$eventListener = new EventListener("onclick",'Tree.select(this.parentNode.parentNode);');
			$newTreeNode->addEventListener($eventListener);
			
			if($subPPList->length > 0) {
				$childsHaveValue = $this->getSectionMenu($newTreeNode,$sectionID,$projectDOM,$projectXpath);	
			}else{
				$childsHaveValue = false;
			}
			if($childsHaveValue  || $sectionHasValue) {
				$p_node->appendChild($newTreeNode);
				$isVisible = true;
			}
		}
		if($isVisible) {
			return true;
		} else {
			return false;
		}
	}
	
	public function getSectionStatusImg($p_sectionID) {
			ob_start();
		if(!isset($_SESSION["Config"]) && !isset($_SESSION["Config"]["General"]) && !isset($_SESSION["Config"]["General"]["PublishImagePath"])){
		$MISConfig = new MISConfig();
        $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
        $projectDOM->load($MISConfig->getConfigFile());
        $projectXpath = new DOMXpath($projectDOM);
		$_SESSION["Config"]["General"]["PublishImagePath"] = $projectXpath->query('/Configuration/General/PublishImagePath')->item(0)->nodeValue;
		}
		$publishImagePath = $_SESSION["Config"]["General"]["PublishImagePath"];

		
		$datensatz = array();
		$dom = new DOMDocument('1.0', 'iso-8859-1');
	   
		$dom->load(utf8_decode($publishImagePath . $this->getUsername() . "/data.xml"));
		$xpath = new DOMXPath($dom);
		$berichte = $xpath->query('/Daten/child::*[@ID = ' . $p_sectionID . ']/Scorecards/Bericht');
	
		for ( $i = 0; $i < $berichte->length; $i++ ) {
			   $element = $berichte->item($i);
			   $wert = $xpath->query('Wert', $element)->item(0)->nodeValue;
			   $hoherzielwert = $xpath->query('HoherZielwert', $element)->item(0)->nodeValue;
	
			   $niedrigerwert = $xpath->query('NiedrigerWert', $element)->item(0)->nodeValue;
	
			   $hoherwert = $xpath->query('HoherWert', $element)->item(0)->nodeValue;
	           $ampel = getImgAlarmstufeSrc($wert, $niedrigerwert, $hoherwert, $hoherzielwert);
	           array_push($datensatz, $ampel);
		}
	   
		$matrix = array(array(1,1,6,6),array(1,8,6,13),array(8,1,13,6),array(8,8,13,13),
	                   array(15,1,20,6),array(15,8,20,13),array(22,1,27,6),
	                   array(22,8,27,13),array(29,1,34,6),array(29,8,34,13),
	                   array(36,1,41,6),array(36,8,41,13),array(43,1,48,6),array(43,8,48,13));
	
		$anzahl = count($datensatz);
		if ($anzahl < 14) {
	        $start = 14 - $anzahl;
		} else {
	        $start = 0;
		}

		$farbe['g1'] = array(66, 206, 0);
		$farbe['g2'] = array(0, 189, 0);
		$farbe['g3'] = array(0, 189, 0);
		$farbe['g4'] = array(0, 156, 0);
		$farbe['g5'] = array(0, 156, 0);
		$farbe['g6'] = array(0, 115, 0);
		$farbe['g7'] = array(0, 99, 0);
		$farbe['r1'] = array(255, 189, 0);
		$farbe['r2'] = array(255, 156, 0);
		$farbe['r3'] = array(255, 99, 0);
		$farbe['r4'] = array(255, 33, 0);
		$farbe['r5'] = array(255, 33, 0);
		$farbe['r6'] = array(206, 0, 0);
		$farbe['r7'] = array(173, 0, 0);
		$farbe['r8'] = array(173, 0, 0);
	    $error = ob_get_clean();
	    if($error =="") {
	   	$im = new Imagick("./img/MISView/sectionStatus.png");
		$i=0;
		foreach ($datensatz as $key => $value) {
		     if (($start > $key)) {
				$draw = new ImagickDraw();
				$draw->setFillColor(new ImagickPixel( 'rgb('.implode(",",$farbe[$value]).')' ));
				$draw->rectangle($matrix[$i][0],$matrix[$i][1],$matrix[$i+1][2],$matrix[$i+1][3]);
				$im->drawImage($draw);
				$i+=2;
        	} else {
				$draw = new ImagickDraw();
				$draw->setFillColor(new ImagickPixel( 'rgb('.implode(",",$farbe[$value]).')' ));
				$draw->rectangle($matrix[$i][0],$matrix[$i][1],$matrix[$i][2],$matrix[$i][3]);
				$im->drawImage($draw);
				$i++;
        	}
		}
	    }else {
			$im = new Imagick("./img/MISView/sectionStatusError.png");
		}
		$data = $im->getImageBlob ();

		header ("Content-Type: image/{$im->getImageFormat()}");
		echo $data; 
	}
	
	private function reports($p_sectionID,$p_reportID=null) {
		$MISConfig = new MISConfig();
		$projectDOM = new DOMDocument('1.0', 'iso-8859-1');
		$projectDOM->load($MISConfig->getConfigFile());
		$projectXpath = new DOMXpath($projectDOM);

		$reportList = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./../../@ID='".$p_sectionID."' and ./Directory='".$this->getUsername()."\\' and ./Active='J']");
		
		$tree = new Tree("contentMenu");

		$prevReportID = $nextReportID = null;
		for($i=0;$i<$reportList->length;$i++){
			$report = $reportList->item($i);
			$reportName = $report->getElementsByTagName("Name")->item(0)->nodeValue;
			if($report->getElementsByTagName("Ansicht")->item(0)->nodeValue == "Client")
				$icon = new Icon("img/report.png");
			else
				$icon = new Icon("img/pdficon_small.gif");
			$label = new Label($icon,$reportName);
			$node = new TreeNode($label,$p_sectionID."_".$report->getAttribute("ID"));
			$node->addEventListener(new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","reports","'.$p_sectionID.'","'.$report->getAttribute('ID').'");'));			
			$tree->appendChild($node);
			
			if($i==0 && empty($p_reportID)) {
				$p_reportID = $report->getAttribute('ID');
			}
		    if($p_reportID == $report->getAttribute('ID')) {
                if($i>0)$prevReportID = $reportList->item($i-1)->getAttribute('ID');
                if($i+1<$reportList->length)$nextReportID = $reportList->item($i+1)->getAttribute('ID');
            }
		}
		$reportName = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./@ID='".$p_reportID."' and ./Directory='".$this->getUsername()."\\' and ./Active='J']")->item(0)->getElementsByTagname("Name")->item(0)->nodeValue;

		if($this->_getView() == "Client") 
			$reportLabel = new Label(new Icon("img/report.png"),$this->_getI18N("reports"));
		else 
			$reportLabel = new Label(new Icon("img/pdficon_small.gif"),$this->_getI18N("reports"));
		$reportLink = '<div class="contentItem" style="background:#A3A3A3;">'.$reportLabel.'</div>';
		
		$scorecardList = $projectXpath->query("/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID='".$p_sectionID."' and ./../../@Directory='".$this->getUsername()."\\']");
		if($scorecardList->length > 0) {
			$scorecardLabel = new Label(new Icon('img/scorecard.png'),$this->_getI18N('scorecards'));
			$scorecardLink = '<div class="contentItem" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'scorecards\\\',\\\''.$p_sectionID.'\\\');">'.$scorecardLabel.'</div>';
		} else {
			$scorecardLink = '';
		}
		
	    $dashboardList = $projectXpath->query("/Configuration/Dashboards/Dashboard[./@ID='".$p_sectionID."']/Reviews/Review[./../../@Directory='".$this->getUsername()."\\']");
        if($dashboardList->length > 0) {
            $dashboardLabel = new Label(new Icon('img/dashboard.png'),$this->_getI18N('dashboards'));
            $dashboardLink = '<div class="contentItem" style="" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'dashboards\\\',\\\''.$p_sectionID.'\\\');">'.$dashboardLabel.'</div>';
        }else{
            $dashboardLink = '';
        }
		$sectionName = $projectXpath->query("/Configuration/Publishes/Publish[@ID='".$p_sectionID."']")->item(0)->getAttribute("Name");
		$tpl = $this->Template();
		if($prevReportID != null){
		      $icon = new Icon("img/MISView/zurueck.gif");
              $icon->addEventListener(new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","reports","'.$p_sectionID.'","'.$prevReportID.'");'));
              $tpl->assign("prevLink",$icon);
		}
		if($nextReportID != null) {
              $icon = new Icon("img/MISView/vor.gif");
              $icon->addEventListener(new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","reports","'.$p_sectionID.'","'.$nextReportID.'");'));
              $tpl->assign("nextLink",$icon);
		}
		

	    $report = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./Active = 'J' and ./@ID = '".$p_reportID."' and ./Directory='".$this->getUsername()."\\']")->item(0);
        $reportPath = $projectXpath->query("/Configuration/General/ReportPath")->item(0)->nodeValue;
        $ppx = $report->getElementsByTagName("ppx")->item(0)->nodeValue;
        $reportFile = $report->getElementsByTagName("Report")->item(0)->nodeValue;
        if($report->getElementsByTagName("Ansicht")->item(0)->nodeValue == "Client") {
	        if($ppx == "J" && file_exists($reportPath.$reportFile.".ppx")) $filename = $reportPath.$reportFile.".ppx"; 
	        else $filename = utf8_decode($reportPath.$reportFile.".ppr");
        }else{
        	if(!isset($_SESSION["Config"]) && !isset($_SESSION["Config"]["General"]) && !isset($_SESSION["Config"]["General"]["PublishImagePath"])){
				$_SESSION["Config"]["General"]["PublishImagePath"] = $projectXpath->query('/Configuration/General/PublishImagePath')->item(0)->nodeValue;
			}
			$publishImagePath = $_SESSION["Config"]["General"]["PublishImagePath"];
            
            $filename = utf8_decode($publishImagePath.$this->getUsername()."\\".$sectionName."\\".$reportName.".pdf");
        } 
        if (!file_exists($filename)) {
            $tpl->assign("reportLink",'javascript:alert(\''.$this->_getI18N('missingReportFile').'\');');
        }else{
            $tpl->assign("reportLink",'?&rc=MISView&rm=getReport&ras[]='.$p_reportID);
        }
        
		$reportList = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./@ID='".$p_reportID."' and ./Directory='".$this->getUsername()."\\']");
		if($reportList->length == 2)
		  $tpl->assign("imageLink",'?&rc=MISView&rm=reportPreview&ras[]='.$p_sectionID.'&ras[]='.$p_reportID);
		else
		  $tpl->assign("imageLink",'?&rc=MISView&rm=reportPreview&ras[]=NAN');
		
	                                      $PPHauptampel = $projectXpath->query('/Configuration/Publishes/Publish/@Alert[./../@ID="'.$p_sectionID.'"]')->item(0)->nodeValue;
                                        if($PPHauptampel == "true") {
                                            $icon = new Icon("?&rc=MISView&rm=getSectionStatusImg&ras[]=".$p_sectionID);
                                            $eventListener = new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","scorecards","'.$p_sectionID.'");');
                                            $icon->addEventListener($eventListener);
                                            $locLabel = new Label($icon,str_replace("_"," ",$sectionName));
                                        }else{
                                            $locLabel = new Label(str_replace("_"," ",$sectionName));
                                        }
        $mainLabel = new Label(str_replace("_"," ",$reportName));
        
        $evalArr = array('CMgr.getMODEL().setLocationName(\''.addslashes($locLabel).'\')',
                  'CMgr.getMODEL().setMainHead(\''.addslashes($mainLabel).'\')',
                  'CMgr.getMODEL().setNavContainer(\''.addslashes(''.$tree.'').'\')',
                  'Tree.setToUserView(Browser.getElementById("contentMenu"));',
                  'Tree.select(null,Browser.getElementById(\''.$p_sectionID."_".$p_reportID.'\'));',
		
		          'CMgr.getMODEL().setMainToolbar(\''.$reportLink.$scorecardLink.$dashboardLink.'\')');
		return array($tpl->fetch('report.tpl'),$evalArr);
	}
	
	public function reportPreview($p_sectionID,$p_reportID=null) {
		
		if($this->getAuth()) {
		if(!isset($_SESSION["Config"]) && !isset($_SESSION["Config"]["General"]) && !isset($_SESSION["Config"]["General"]["PublishImagePath"])){
		$MISConfig = new MISConfig();
        $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
        $projectDOM->load($MISConfig->getConfigFile());
        $projectXpath = new DOMXpath($projectDOM);
		$_SESSION["Config"]["General"]["PublishImagePath"] = $projectXpath->query('/Configuration/General/PublishImagePath')->item(0)->nodeValue;
		}
		$publishImagePath = $_SESSION["Config"]["General"]["PublishImagePath"];
		
			$p_args = func_get_args();
			$MISConfig = new MISConfig();
			$projectDOM = new DOMDocument('1.0', 'iso-8859-1');
			$projectDOM->load($MISConfig->getConfigFile());
			$projectXpath = new DOMXpath($projectDOM);
			$filename= "";
			if($p_sectionID != "NAN"){		
			    
				$imageNodeListGif = $projectXpath->query('/Configuration/Publishes/Publish/Images/Image[./../../@ID = "'.$p_sectionID.'" and ./@ID = "'.$p_reportID.'" and ./Directory = "'.$this->getUsername().'\\" and ./Active = "N" and ./GIFGenerate = "J"]');
				$imageNodeListJpg = $projectXpath->query('/Configuration/Publishes/Publish/Images/Image[./../../@ID = "'.$p_sectionID.'" and ./@ID = "'.$p_reportID.'" and ./Directory = "'.$this->getUsername().'\\" and ./Active = "N" and ./JPGGenerate = "J"]');
				
				$reportName = $projectXpath->query('/Configuration/Publishes/Publish/Images/Image/Name[./../../../@ID="'.$p_sectionID.'" and ./../@ID = "'.$p_reportID.'" and ./../Directory = "'.$this->getUsername().'\\" and ./../Active = "N"]')->item(0)->nodeValue;
				
				$sectionName = $projectXpath->query("/Configuration/Publishes/Publish[./@ID='".$p_sectionID."']")->item(0)->getAttribute("Name");
								
				if(count($imageNodeListGif) > 0) {
					$filename = $publishImagePath.$this->getUsername()."/".$sectionName."/".$reportName.".gif";
					$file_extension = "gif";
				} else if(count($imageNodeListJpg) > 0) {
					$filename = $publishImagePath.$this->getUsername()."/".$sectionName."/".$reportName.".png";
					$file_extension = "jpg";
				}
			}
			
	        $filename = utf8_decode($filename);
		    if (file_exists($filename)) {

		        $im = new Imagick($filename);
			    $im->scaleImage(750,0);
/*
	            if(date('j-m-y',time()) > date('j-m-y',filemtime(utf8_decode($publishImagePath.$this->getUsername()."/data.xml")))+3) {

				    $draw = new ImagickDraw();
				
				    $draw->setFont( "SociaLAnimaL" );
				    
				    $draw->setFillColor(new ImagickPixel('red'));
				
				    $draw->setFontSize( 45 );
				
				    $draw->setFillAlpha( 0.7 );
				
				    $draw->setGravity( Imagick::GRAVITY_CENTER );
				
				    $im->annotateImage( $draw, 0, 0, 25, "BERICHT IST NICHT AKTUELL!" );
				    
				    $im->annotateImage( $draw, 0, 65, 15, "STAND: ".date('j.m.y',filemtime(ROOT_DIR."daten/".$this->getUsername()."/data.xml")) );
			    
	             }
*/			}else{
                $im = new Imagick();
                $im->setResolution(750,500);
                $im->newImage(750, 500, new ImagickPixel('white'));
                
                    /* Create a drawing object and set the font size */
                    $draw = new ImagickDraw();
                
                    /*** set the font ***/
                    $draw->setFont( "SociaLAnimaL" );
                    
                    /*** set color ***/
                    $draw->setFillColor(new ImagickPixel('red'));
                
                    /*** set the font size ***/
                    $draw->setFontSize( 30 );
                
                    /*** add some transparency ***/
                    $draw->setFillAlpha( 0.7 );
                
                    /*** set gravity to the center ***/
                    $draw->setGravity( Imagick::GRAVITY_CENTER );
                
                    /*** overlay the text on the image ***/
                    $im->annotateImage( $draw, 0, -30, 0, $this->_getI18N("noPreview") );
                    $im->annotateImage( $draw, 0, +30, 0, $this->_getI18N("clickToOpen") );
                    
                    $im->setImageFormat('png');
                    
                    /*** set the font size ***/
                    //$im->annotateImage( $draw, 0, 65, 15, "STAND: ".date('j.m.y',filemtime(ROOT_DIR."daten/".$this->getUsername()."/data.xml")) );
			}

	           header("Pragma: public");
	           header("Expires: 0");
	           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	           header("Cache-Control: private",false);
	           header ("Content-Type: image/".$im->getImageFormat());
			 $data = $im->getImageBlob ();
			 echo $data; 
		}
	}
	
	public function getReport($p_reportID) {
		if($this->getAuth()) {
			$p_args = func_get_args();
			$MISConfig = new MISConfig();
			$projectDOM = new DOMDocument('1.0', 'iso-8859-1');
			$projectDOM->load($MISConfig->getConfigFile());
			$projectXpath = new DOMXpath($projectDOM);
			$report = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./Active = 'J' and ./@ID = '".$p_reportID."']")->item(0);
			
			
			$ansicht = $report->getElementsByTagName("Ansicht")->item(0)->nodeValue;
			
			//$ansicht = $this->_getView();
	
			switch($ansicht) {
				case "Client":	$name = $report->getElementsByTagName("Report")->item(0)->nodeValue;
								$reportPath = $projectXpath->query("/Configuration/General/ReportPath")->item(0)->nodeValue;
								$ppx = $report->getElementsByTagName("ppx")->item(0)->nodeValue;
                                if($ppx == "J" && file_exists($reportPath.$name.".ppx")) $filename = utf8_decode($reportPath.$name.".ppx"); 	
					            else $filename = utf8_decode($reportPath.$name.".ppr");

					            $file_extension = strtolower(substr(strrchr($filename,"."),1));
	
					            switch ($file_extension) {
					                case "pdf": $ctype="application/pdf"; break;
					                case "exe": $ctype="application/octet-stream"; break;
					                case "zip": $ctype="application/zip"; break;
					                case "doc": $ctype="application/msword"; break;
					                case "xls": $ctype="application/vnd.ms-excel"; break;
					                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
					                case "gif": $ctype="image/gif"; break;
					                case "png": $ctype="image/png"; break;
					                case "jpe": case "jpeg":
					                case "jpg": $ctype="image/jpeg"; break;
					                case "ppr": $ctype="application/powerplay"; break;
					                case "ppx": $ctype="application/powerplay"; break;
					                default: $ctype="text";
					            }
			                    if (!file_exists($filename)) {
                                    die("<script type='text/javascript'>alert('" .$this->_getI18N("missingReportFile")."');window.history.back();</script>");
                                }					            
					
					            header("Pragma: public");
					            header("Expires: 0");
					            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
					            header("Cache-Control: private",false);
					            header("Content-Type: $ctype");
					            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
					            header("Content-Transfer-Encoding: binary");
					            header("Content-Length: ".@filesize($filename));
					            set_time_limit(0);
					            readfile($filename) or die("File not found."); 
					            break;
				case "Info-User":$name = $report->getElementsByTagName("Name")->item(0)->nodeValue;
								$reportPath = $projectXpath->query("/Configuration/General/PublishImagePath")->item(0)->nodeValue;
								$sectionName = $projectXpath->query("/Configuration/Publishes/Publish[./Images/Image/@ID = '".$p_reportID."']")->item(0);	
					            $filename = utf8_decode($reportPath.$this->getUsername()."\\".$sectionName->getAttribute("Name")."\\".$name.".pdf");
	
					            $file_extension = strtolower(substr(strrchr($filename,"."),1));
								$filename = $filename;
					            switch ($file_extension) {
					                case "pdf": $ctype="application/pdf"; break;
					                case "exe": $ctype="application/octet-stream"; break;
					                case "zip": $ctype="application/zip"; break;
					                case "doc": $ctype="application/msword"; break;
					                case "xls": $ctype="application/vnd.ms-excel"; break;
					                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
					                case "gif": $ctype="image/gif"; break;
					                case "png": $ctype="image/png"; break;
					                case "jpe": break;
					                case "jpeg":break;
					                case "jpg": $ctype="image/jpeg"; break;
					                case "ppr": $ctype="application/powerplay"; break;
					                default: $ctype="text";
					            }
						        if (!file_exists($filename)) {
						            die("<script type='text/javascript'>alert('".$this->_getI18N("missingReportFile")."');window.history.back();</script>");
						        }
					
					            header("Pragma: public");
					            header("Expires: 0");
					            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
					            header("Cache-Control: private",false);
					            header("Content-Type: $ctype");
					            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
					            header("Content-Transfer-Encoding: binary");
					            header("Content-Length: ".@filesize($filename));
					            set_time_limit(0);
					            readfile($filename) or die("File not found."); 
					            break;
				case "Web":		print "WRONG VIEW MODE!"; break;
				default:		print "COULDN'T VALIDATE YOUR USER INFORMATION! PLEASE CONTACT YOUR ADMINISTRATOR!"; break;
			}		
		}else{
			print "<script type='text/javascript'>window.history.back();</script>";
		}
	}
	
	public function getScorecardStatusImg($p_sectionID,$p_scorecardID) {
        try {
		$MISConfig = new MISConfig();
        $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
        $projectDOM->load($MISConfig->getConfigFile());
        $projectXpath = new DOMXpath($projectDOM);
        $publishImagePath = $projectXpath->query('/Configuration/General/PublishImagePath')->item(0)->nodeValue;
		$dataDOM = new DOMDocument('1.0', 'iso-8859-1');
		$dataDOM->load(utf8_decode($publishImagePath.$this->getUsername()."/data.xml"));
		$dataXpath = new DOMXpath($dataDOM);
		
		$report = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[../../@ID = "'.$p_sectionID.'"]')->item($p_scorecardID);
		
	    $aktwert = $report->getElementsByTagName("Wert")->item(0)->nodeValue;
	    $niedriger = $report->getElementsByTagName("NiedrigerWert")->item(0)->nodeValue;
	    $hoher = $report->getElementsByTagName("HoherWert")->item(0)->nodeValue;
	    $positiv = $report->getElementsByTagName("HoherZielwert")->item(0)->nodeValue;
		$farbe = getImgAlarmstufeSrc($aktwert,$niedriger,$hoher,$positiv);

		$im = new Imagick(ROOT_DIR."apps/MISView/images/".$farbe.".gif");

		header ("Content-Type: image/{$im->getImageFormat()}");
		$data = $im->getImageBlob ();
        }catch(Exception $e) {
        $im = new Imagick(ROOT_DIR."apps/MISView/images/gerror.gif");

        header ("Content-Type: image/{$im->getImageFormat()}");
        $data = $im->getImageBlob ();
        }
		echo $data; 
		
	}
	
	private function scorecards($p_sectionID,$p_scorecardID=0) {
		$MISConfig = new MISConfig();
		$projectDOM = new DOMDocument('1.0', 'iso-8859-1');
		$projectDOM->load($MISConfig->getConfigFile());
		$projectXpath = new DOMXpath($projectDOM);

		$publishImagePath = $projectXpath->query('/Configuration/General/PublishImagePath')->item(0)->nodeValue;
		
		$dataDOM = new DOMDocument('1.0', 'iso-8859-1');
		$dataDOM->load(utf8_decode($publishImagePath.$this->getUsername()."/data.xml"));
		$dataXpath = new DOMXpath($dataDOM);
		
		$p_reportID = $projectXpath->query('/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID = "'.$p_sectionID.'"]')->item($p_scorecardID)->getAttribute("ID");
		$scorecardList = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[./../../@ID = "'.$p_sectionID.'"]');
		
		$tree = new Tree("contentMenu");
		
		for($i=0;$i<$scorecardList->length;$i++){
			$report = $scorecardList->item($i);
			$reportName = $report->getElementsByTagName("Titel")->item(0)->nodeValue;
			$icon = new Icon("?&rc=MISView&rm=getScorecardStatusImg&ras[]=".$p_sectionID."&ras[]=".$i);
			$label = new Label($icon,$reportName);
			$temp = $projectXpath->query('/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID = "'.$p_sectionID.'"]')->item($i)->getAttribute("ID");
			$node = new TreeNode($label,$p_sectionID."_".$temp);
			$node->addEventListener(new EventListener("onclick",'Tree.select(this.parentNode.parentNode);CMgr.getMODEL().getMain("MISView","scorecards","'.$p_sectionID.'","'.$i.'");'));
			$tree->appendChild($node);
			if($i==0 && empty($p_scorecardID)) {
				$p_reportID = $temp;
                $active_reportName = $reportName;
			}			
		    if($i==$p_scorecardID) {
                $p_reportID = $temp;
                $active_reportName = $reportName;
            }

		}
		
		
		
		$scorecardLabel = new Label(new Icon('img/scorecard.png'),$this->_getI18N('scorecards'));
        $scorecardLink = '<div class="contentItem" style="background:#A3A3A3;">'.$scorecardLabel.'</div>';
        
		$reportList = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./../../@ID='".$p_sectionID."' and ./Directory='".$this->getUsername()."\' and ./Active='J']");
		if($reportList->length > 0) {
			if($this->_getView() == "Client")
				$icon = new Icon("img/report.png");
			else
				$icon = new Icon("img/pdficon_small.gif");
			$reportLabel = new Label($icon,$this->_getI18N("reports"));
			$reportLink = '<div class="contentItem" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'reports\\\',\\\''.$p_sectionID.'\\\');">'.$reportLabel.'</div>';
		}else{
			$reportLink ='';
		}
		
		$dashboardList = $projectXpath->query("/Configuration/Dashboards/Dashboard[./@ID='".$p_sectionID."']/Reviews/Review[./../../@Directory='".$this->getUsername()."\']");
		if($dashboardList->length > 0) {
			$dashboardLabel = new Label(new Icon('img/dashboard.png'),$this->_getI18N('dashboards'));
		    $dashboardLink = '<div class="contentItem" style="" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'dashboards\\\',\\\''.$p_sectionID.'\\\');">'.$dashboardLabel.'</div>';
		}else{
			$dashboardLink = '';
		}
		
		$sectionName = $projectXpath->query("/Configuration/Publishes/Publish[@ID='".$p_sectionID."']")->item(0)->getAttribute("Name");
		
		$tpl = $this->Template();
		$scorecard = $scorecardList->item($p_scorecardID);
        $tpl->assign("reportLink",'?&rc=MISView&rm=getScorecard&ras[]='.$projectXpath->query("/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID = '".$p_sectionID."']")->item($p_scorecardID)->getAttribute("ID"));
		$tpl->assign('sectionID',$p_sectionID);
		$tpl->assign('ID',$projectXpath->query("/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID = '".$p_sectionID."']")->item($p_scorecardID)->getAttribute("ID"));
		$tpl->assign('item',$p_scorecardID);
		$tpl->assign('Name',array('desc'=>$this->_getI18N('name'),'value'=>$scorecard->getElementsByTagname("Titel")->item(0)->nodeValue));
		$tpl->assign('Description',array('desc'=>$this->_getI18N('description'),'value'=>$scorecard->getElementsByTagName("Beschreibung")->item(0)->nodeValue));
		$tpl->assign('Status',array('desc'=>$this->_getI18N('status'),'value'=>'?&rc=MISView&rm=getScorecardDetailStatusImg&ras[]='.$p_sectionID.'&ras[]='.$p_scorecardID));
		$tpl->assign('Value',array('desc'=>$this->_getI18N('value'),'value'=>$scorecard->getElementsByTagName("Wert")->item(0)->nodeValue));
		$tpl->assign('HighValue',array('desc'=>$this->_getI18N('highValue'),'value'=>$scorecard->getElementsByTagName("HoherWert")->item(0)->nodeValue));
		$tpl->assign('LowValue',array('desc'=>$this->_getI18N('lowValue'),'value'=>$scorecard->getElementsByTagName("NiedrigerWert")->item(0)->nodeValue));
		$tpl->assign('Tolerance',array('desc'=>$this->_getI18N('tolerance'),'value'=>$scorecard->getElementsByTagName("Toleranz")->item(0)->nodeValue));
		$tpl->assign('Weight',array('desc'=>$this->_getI18N('weight'),'value'=>$scorecard->getElementsByTagName("Gewichtung")->item(0)->nodeValue));
		$tpl->assign('PositiveValue',array('desc'=>$this->_getI18N('positiveValue'),'value'=>$scorecard->getElementsByTagName("HoherZielwert")->item(0)->nodeValue));
		$tpl->assign('Coordinates',array('desc'=>$this->_getI18N('coordinates'),'value'=>$scorecard->getElementsByTagName("Koordinaten")->item(0)->nodeValue));
		$tpl->assign('SAVE',$this->_getI18N("save"));
		$tpl->assign('OPEN_REPORT',$this->_getI18N("open_report"));

	                                        $PPHauptampel = $projectXpath->query('/Configuration/Publishes/Publish/@Alert[./../@ID="'.$p_sectionID.'"]')->item(0)->nodeValue;
                                        if($PPHauptampel == "true") {
                                            $icon = new Icon("?&rc=MISView&rm=getSectionStatusImg&ras[]=".$p_sectionID);
                                            $eventListener = new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","scorecards","'.$p_sectionID.'");');
                                            $icon->addEventListener($eventListener);
                                            $newLabel = new Label($icon,str_replace("_"," ",$sectionName));
                                        }else{
                                            $newLabel = new Label(str_replace("_"," ",$sectionName));
                                        }
		$evalArr = array('CMgr.getMODEL().setLocationName(\''.addslashes($newLabel).'\')',
                  'CMgr.getMODEL().setMainHead(\''.addslashes(new Label(str_replace("_"," ",$scorecard->getElementsByTagname("Titel")->item(0)->nodeValue))).'\')',
		          'CMgr.getMODEL().setNavContainer(\''.addslashes($tree).'\')',
		          'CMgr.getMODEL().setMainToolbar(\''.$reportLink.$scorecardLink.$dashboardLink.'\');',
                  'Tree.setToUserView(Browser.getElementById("contentMenu"));',
                  'Tree.select(null,Browser.getElementById(\''.$p_sectionID."_".$p_reportID.'\'));',

		          'CMgr.getMODEL().setMainFootbar(\'\');');
		return array($tpl->fetch("scorecard.tpl"),implode(";",$evalArr));
	}
	
    public function saveScorecard($p_sectionID,$p_ID,$p_item,$p_highValue,$p_lowValue) {
        $MISConfig = new MISConfig();       
        $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
        $projectDOM->load($MISConfig->getConfigFile());
        $projectXpath = new DOMXpath($projectDOM);
        
        $publishImagePath = $projectXpath->query('/Configuration/General/PublishImagePath')->item(0)->nodeValue;
        
        $dataDOM = new DOMDocument('1.0', 'iso-8859-1');
        $dataDOM->load(utf8_decode($publishImagePath.$this->getUsername()."/data.xml"));
        $dataXpath = new DOMXpath($dataDOM);

        
        $PR = $projectXpath->query('/Configuration/Scorecards/Scorecard/Reports/Report[./@ID = "'.$p_ID.'"]')->item(0);
        if($PR->getElementsByTagName("Format")->item(0)->nodeValue == "Prozent") {
        	        $p_lowValue = str_replace("%","",$p_lowValue);
        $p_highValue = str_replace("%","",$p_highValue);
        
	        $MISConfig->setNodeValue("LowValue",number_reformat($p_lowValue, 2, ',',".")/100,$projectDOM,$PR);
	        $MISConfig->setNodeValue("HighValue",number_reformat($p_highValue, 2, ',',".")/100,$projectDOM,$PR);
	        $PRR = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[./../../@ID="'.$p_sectionID.'"]')->item($p_item);
	        
	        $MISConfig->setNodeValue("NiedrigerWert",str_replace(".",",",number_reformat($p_lowValue, 2, ',',"."))." %",$dataDOM,$PRR);
	        $MISConfig->setNodeValue("HoherWert",str_replace(".",",",number_reformat($p_highValue, 2, ',',"."))." %",$dataDOM,$PRR);
        }
        
        if($PR->getElementsByTagName("Format")->item(0)->nodeValue == "Ganzzahlig") {
            $MISConfig->setNodeValue("LowValue",number_reformat($p_lowValue, 0, ',',"."),$projectDOM,$PR);
            $MISConfig->setNodeValue("HighValue",number_reformat($p_highValue, 0, ',',"."),$projectDOM,$PR);
            $PRR = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[./../../@ID="'.$p_sectionID.'"]')->item($p_item);
            
            $MISConfig->setNodeValue("NiedrigerWert",str_replace(".",",",number_reformat($p_lowValue, 0, ',',"."))."",$dataDOM,$PRR);
            $MISConfig->setNodeValue("HoherWert",str_replace(".",",",number_reformat($p_highValue, 0, ',',"."))."",$dataDOM,$PRR); 
        }
        
        if($PR->getElementsByTagName("Format")->item(0)->nodeValue == "Zahl mit Trennz") {
            $MISConfig->setNodeValue("LowValue",number_reformat($p_lowValue, 2, ',',"."),$projectDOM,$PR);
            $MISConfig->setNodeValue("HighValue",number_reformat($p_highValue, 2, ',',"."),$projectDOM,$PR);
            $PRR = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[./../../@ID="'.$p_sectionID.'"]')->item($p_item);
            
            $MISConfig->setNodeValue("NiedrigerWert",str_replace(".",",",number_reformat($p_lowValue, 2, ',',"."))."",$dataDOM,$PRR);
            $MISConfig->setNodeValue("HoherWert",str_replace(".",",",number_reformat($p_highValue, 2, ',',"."))."",$dataDOM,$PRR);
        }
        
        if($PR->getElementsByTagName("Format")->item(0)->nodeValue == "Zahl ohne Trennz") {
            $MISConfig->setNodeValue("LowValue",number_reformat($p_lowValue, 0, ',',"."),$projectDOM,$PR);
            $MISConfig->setNodeValue("HighValue",number_reformat($p_highValue, 0, ',',"."),$projectDOM,$PR);
            $PRR = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[./../../@ID="'.$p_sectionID.'"]')->item($p_item);
            
            $MISConfig->setNodeValue("NiedrigerWert",str_replace(".",",",number_reformat($p_lowValue, 0, ',',"."))."",$dataDOM,$PRR);
            $MISConfig->setNodeValue("HoherWert",str_replace(".",",",number_reformat($p_highValue, 0, ',',"."))."",$dataDOM,$PRR);
        }
        
        if($PR->getElementsByTagName("Format")->item(0)->nodeValue == "W�hrung") {
            $MISConfig->setNodeValue("LowValue",number_reformat($p_lowValue, 2, ',',"."),$projectDOM,$PR);
            $MISConfig->setNodeValue("HighValue",number_reformat($p_highValue, 2, ',',"."),$projectDOM,$PR);
            $PRR = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[./../../@ID="'.$p_sectionID.'"]')->item($p_item);
            
            $MISConfig->setNodeValue("NiedrigerWert",str_replace(".",",",number_reformat($p_lowValue, 2, ',',"."))."",$dataDOM,$PRR);
            $MISConfig->setNodeValue("HoherWert",str_replace(".",",",number_reformat($p_highValue, 2, ',',"."))."",$dataDOM,$PRR);
        }
        $dataDOM->save(utf8_decode($publishImagePath.$this->getUsername()."/data.xml"));
        $projectDOM->save($MISConfig->getConfigFile());
        return array('CMgr.getMODEL().__construct();');     
    }
    public function getScorecard($p_reportID) {
        if($this->getAuth()) {
            $p_args = func_get_args();
            $MISConfig = new MISConfig();
            $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
            $projectDOM->load($MISConfig->getConfigFile());
            $projectXpath = new DOMXpath($projectDOM);
            $report = $projectXpath->query("/Configuration/Scorecards/Scorecard/Reports/Report[./@ID = '".$p_reportID."' and ./../../@Directory='".$this->getUsername()."\\']")->item(0);
            
            
            //$ansicht = $report->getElementsByTagName("Ansicht")->item(0)->nodeValue;

               $name = $report->getElementsByTagName("ReportFile")->item(0)->nodeValue;
                                $reportPath = $projectXpath->query("/Configuration/General/ReportPath")->item(0)->nodeValue;    
                                $filename = $reportPath.$name.".ppr";
    
                                $file_extension = strtolower(substr(strrchr($filename,"."),1));
    
                                switch ($file_extension) {
                                    case "pdf": $ctype="application/pdf"; break;
                                    case "exe": $ctype="application/octet-stream"; break;
                                    case "zip": $ctype="application/zip"; break;
                                    case "doc": $ctype="application/msword"; break;
                                    case "xls": $ctype="application/vnd.ms-excel"; break;
                                    case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                                    case "gif": $ctype="image/gif"; break;
                                    case "png": $ctype="image/png"; break;
                                    case "jpe": case "jpeg":
                                    case "jpg": $ctype="image/jpeg"; break;
                                    case "ppr": $ctype="application/powerplay"; break;
                                    default: $ctype="text";
                                }
                                if (!file_exists($filename)) {
                                    die("<script type='text/javascript'>alert('".$this->_getI18N("missingReportFile")."');window.history.back();</script>");
                                }                               
                    
                                header("Pragma: public");
                                header("Expires: 0");
                                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                                header("Cache-Control: private",false);
                                header("Content-Type: $ctype");
                                header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
                                header("Content-Transfer-Encoding: binary");
                                header("Content-Length: ".@filesize($filename));
                                set_time_limit(0);
                                readfile($filename) or die("File not found."); 
   
        }else{
            print "<script type='text/javascript'>window.history.back();</script>";
        }
    }
	
	public function getScorecardDetailStatusImg($p_sectionID,$p_scorecardID) {
		header("Content-Type: image/png\n\n");
		
        $MISConfig = new MISConfig();
        $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
        $projectDOM->load($MISConfig->getConfigFile());
        $projectXpath = new DOMXpath($projectDOM);

        $publishImagePath = $projectXpath->query('/Configuration/General/PublishImagePath')->item(0)->nodeValue;
        
		
		$dataDOM = new DOMDocument('1.0', 'iso-8859-1');
		$dataDOM->load(utf8_decode($publishImagePath.$this->getUsername()."/data.xml"));
		$dataXpath = new DOMXpath($dataDOM);
		
		$scorecard = $dataXpath->query('/Daten/child::*/Scorecards/Bericht[../../@ID = "'.$p_sectionID.'"]')->item($p_scorecardID);
		
	    $anzeige = ImageCreateFromPNG (ROOT_DIR."apps/MISView/scDetail_".$scorecard->getElementsByTagName("HoherZielwert")->item(0)->nodeValue.".png");
	    $pfeil = ImageCreateFromPNG (ROOT_DIR."apps/MISView/dart.png");
	    
	    $faktor = 8;
	    $aktwert = umwandeln($scorecard->getElementsByTagName("Wert")->item(0)->nodeValue);
	    $niedriger = umwandeln($scorecard->getElementsByTagName("NiedrigerWert")->item(0)->nodeValue);
	    $hoher = umwandeln($scorecard->getElementsByTagName("HoherWert")->item(0)->nodeValue);
	
	    $delta = $hoher - $niedriger;
	    if ($scorecard->getElementsByTagName("HoherZielwert")->item(0)->nodeValue == "J") {
	          if (($aktwert > $niedriger) && ($aktwert < $hoher)) {
	               $pixel = ((($aktwert - $niedriger) * 135) / $delta) + 14;
	          } elseif ($aktwert > $hoher) {
	              $pixel = ((($aktwert - $hoher) * 129) / ($delta * $faktor)) + 155;
	          } else {
	               $pixel = 13 + ((($aktwert - $niedriger) * 13) / ($delta * 2));
	          }
	     } else {
	          if (($aktwert > $niedriger) && ($aktwert < $hoher)) {
	               $pixel = ((($aktwert - $niedriger) * 135) / $delta) + 140;
	          } elseif ($aktwert > $hoher) {
	               $pixel = ((($aktwert - $hoher) * 13) / ($delta * 2)) + 270;
	          } else {
	               $pixel = 140 + ((($aktwert - $niedriger) * 129) / ($delta * $faktor));
	          }
	     }
	     $pixel = round($pixel);
	     if ($pixel > 285) {
	          $pixel = 285;
	     }
	     if ($pixel < 0) {
	          $pixel = 0;
	     }	    
	    
	   	ImageCopy ($anzeige, $pfeil, $pixel, 8, 0, 0, 11, 24);
	
	   	$schwarz  = ImageColorAllocate ($anzeige, 0, 0, 0);

	   	if ($scorecard->getElementsByTagName("HoherZielwert")->item(0)->nodeValue == "J") {
	        $minpos = 27;
	        $maxpos = 162;
	   	} else {
	        $minpos = 133 - 6 * strlen($niedriger);
	        $maxpos = 268 - 6 * strlen($hoher);
	   	}
	   	ImageString($anzeige, 2, $minpos, 32, $niedriger, $schwarz);
	   	ImageString($anzeige, 2, $maxpos, 32, $hoher, $schwarz);

	   	ImagePng($anzeige);
	}
	
    private function dashboards($p_sectionID,$p_reportID=null) {
        $MISConfig = new MISConfig();
        $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
        $projectDOM->load($MISConfig->getConfigFile());
        $projectXpath = new DOMXpath($projectDOM);

        $reportList = $projectXpath->query("/Configuration/Dashboards/Dashboard/Reviews/Review[./../../@Directory='".$this->getUsername()."\' and ./../../@ID='".$p_sectionID."']");
        
        $tree = new Tree("contentMenu");

        for($i=0;$i<$reportList->length;$i++){
            $report = $reportList->item($i);
            $reportName = $report->getElementsByTagName("Name")->item(0)->nodeValue;
            $reportDesc = $report->getElementsByTagName("Description")->item(0)->nodeValue;
            $icon = new Icon("img/dashboard.png");
            $label = new Label($icon,$reportName);
            $node = new TreeNode($label,$p_sectionID."_".$report->getAttribute("ID"));
            $node->addEventListener(new EventListener("onclick",'Tree.select(this.parentNode.parentNode);CMgr.getMODEL().getMain("MISView","dashboards","'.$p_sectionID.'","'.$report->getAttribute('ID').'");'));         
            $tree->appendChild($node);
            
            if($i==0 && empty($p_reportID)) {
                $p_reportID = $report->getAttribute('ID');
                $active_reportName = $reportName;
                $active_reportDesc = $reportDesc;
            }
            if($p_reportID == $report->getAttribute('ID')) {
            	//$label->active(true);
            	$active_reportName = $reportName;
                $active_reportDesc = $reportDesc;
            }
        }

        if($this->_getView() == "Client")
			$icon = new Icon("img/report.png");
		else
			$icon = new Icon("img/pdficon_small.gif");
        $reportLabel = new Label($icon,$this->_getI18N("reports"));
        $scorecardLabel = new Label(new Icon('img/scorecard.png'),$this->_getI18N('scorecards'));
        $dashboardLabel = new Label(new Icon('img/dashboard.png'),$this->_getI18N('dashboards'));
        $reportList = $projectXpath->query("/Configuration/Publishes/Publish/Images/Image[./Directory='".$this->getUsername()."\' and ./../../@ID='".$p_sectionID."']");
        if($reportList->length > 0) {
            $reportLink = '<div class="contentItem" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'reports\\\',\\\''.$p_sectionID.'\\\');">'.$reportLabel.'</div>';
        }else{
        	$reportLink = "";
        }
        $dashboardLink = '<div class="contentItem" style="background:#A3A3A3;">'.$dashboardLabel.'</div>';
        
        $scorecardList = $projectXpath->query("/Configuration/Scorecards/Scorecard/Reports/Report[./../../@ID='".$p_sectionID."' and ./../../@Directory='".$this->getUsername()."\\']");
        if($scorecardList->length > 0) {
            $scorecardLink = '<div class="contentItem" onclick="CMgr.getMODEL().getMain(\\\'MISView\\\',\\\'scorecards\\\',\\\''.$p_sectionID.'\\\');">'.$scorecardLabel.'</div>';
        } else {
            $scorecardLink = '';
        }
        $sectionName = $projectXpath->query("/Configuration/Publishes/Publish[@ID='".$p_sectionID."']")->item(0)->getAttribute("Name");
        $tpl = $this->Template();
                $tpl->assign('OPEN_REPORT',$this->_getI18N("open_report"));
                $tpl->assign('Description',array('desc'=>$this->_getI18N('description'),'value'=>$active_reportDesc));
        $tpl->assign("reportLink",'?&rc=MISView&rm=getDashboard&ras[]='.$p_reportID);
        $tpl->assign("imageLink",'img/MISView/excel.gif');
                                              $PPHauptampel = $projectXpath->query('/Configuration/Publishes/Publish/@Alert[./../@ID="'.$p_sectionID.'"]')->item(0)->nodeValue;
                                        if($PPHauptampel == "true") {
                                            $icon = new Icon("?&rc=MISView&rm=getSectionStatusImg&ras[]=".$p_sectionID);
                                            $eventListener = new EventListener("onclick",'CMgr.getMODEL().getMain("MISView","scorecards","'.$p_sectionID.'");');
                                            $icon->addEventListener($eventListener);
                                            $newLabel = new Label($icon,str_replace("_"," ",$sectionName));
                                        }else{
                                            $newLabel = new Label(str_replace("_"," ",$sectionName));
                                        }
        $evalArr = array('CMgr.getMODEL().setLocationName(\''.addslashes($newLabel).'\')',
                    'CMgr.getMODEL().setMainHead(\''.addslashes(new Label(str_replace("_"," ",$active_reportName))).'\')',
                  'CMgr.getMODEL().setNavContainer(\''.addslashes(''.$tree.'').'\')',
                  'Tree.setToUserView(Browser.getElementById("contentMenu"));',
                  'Tree.select(null,Browser.getElementById(\''.$p_sectionID."_".$p_reportID.'\'));',
                  'CMgr.getMODEL().setMainToolbar(\''.$reportLink.$scorecardLink.$dashboardLink.'\')',
                  'CMgr.getMODEL().setMainFootbar(\'\');');
        return array($tpl->fetch('dashboard.tpl'),implode(";",$evalArr));
    }
    
    public function getDashboard($p_reportID) {
        if($this->getAuth()) {
            $p_args = func_get_args();
            $MISConfig = new MISConfig();
            $projectDOM = new DOMDocument('1.0', 'iso-8859-1');
            $projectDOM->load($MISConfig->getConfigFile());
            $projectXpath = new DOMXpath($projectDOM);
            $report = $projectXpath->query("/Configuration/Dashboards/Dashboard/Reviews/Review[./@ID = '".$p_reportID."' and ./../../@Directory='".$this->getUsername()."\\']")->item(0);
            
            
            $name = $report->getElementsByTagName("ReportFile")->item(0)->nodeValue;
                                $reportPath = $projectXpath->query("/Configuration/General/DashboardPath")->item(0)->nodeValue;    
                                $filename = $reportPath.$name.".xls";
    
                                $file_extension = strtolower(substr(strrchr($filename,"."),1));
    
                                switch ($file_extension) {
                                    case "pdf": $ctype="application/pdf"; break;
                                    case "exe": $ctype="application/octet-stream"; break;
                                    case "zip": $ctype="application/zip"; break;
                                    case "doc": $ctype="application/msword"; break;
                                    case "xls": $ctype="application/vnd.ms-excel"; break;
                                    case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                                    case "gif": $ctype="image/gif"; break;
                                    case "png": $ctype="image/png"; break;
                                    case "jpe": case "jpeg":
                                    case "jpg": $ctype="image/jpeg"; break;
                                    case "ppr": $ctype="application/powerplay"; break;
                                    default: $ctype="text";
                                }
                                if (!file_exists($filename)) {
                                    die("<script type='text/javascript'>alert('".$this->_getI18N("missingReportFile")."');window.history.back();</script>");
                                }                               
                    
                                header("Pragma: public");
                                header("Expires: 0");
                                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                                header("Cache-Control: private",false);
                                header("Content-Type: $ctype");
                                header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
                                header("Content-Transfer-Encoding: binary");
                                header("Content-Length: ".@filesize($filename));
                                set_time_limit(0);
                                readfile($filename) or die("File not found."); 
                                    
        }else{
            print "<script type='text/javascript'>window.history.back();</script>";
        }
    }
}
?>