<?php

if (strpos($_SERVER['HTTP_USER_AGENT'], 'ms-office') !== false) {
  exit;
}

ob_start();
if(!(is_readable(realpath(dirname(__FILE__)).'/include/includesroutines.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/include/includesroutines.inc');
} else {
	include_once(realpath(dirname(__FILE__)).'/include/includesroutines.inc');
}

$ismob = (isset($_COOKIE['mobilemode']) && $_COOKIE['mobilemode'] == 1);

checkUserAndRedirectToLogin();

$sprtHst = true;
if (((isset($_REQUEST['NotSupportHistory']) && $_REQUEST['NotSupportHistory'] == 1)) ||
	((isset($_SESSION['NotSupportHistory']) && $_SESSION['NotSupportHistory'] == 1)) ){
	$sprtHst = false;
	$_SESSION['NotSupportHistory'] = isset($_REQUEST['NotSupportHistory']) ? $_REQUEST['NotSupportHistory'] : $_SESSION['NotSupportHistory'];
}

if(!(is_readable(realpath(dirname(__FILE__)).'/classes/tree.php'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/classes/tree.php');
} else {
	include_once(realpath(dirname(__FILE__)).'/classes/tree.php');
}

if (isset($_REQUEST['oguid']) ){
	$_SESSION['oguid'] = $_REQUEST['oguid'];
}

if (isset($_REQUEST['rguid'])){
	$_SESSION['rguid'] = $_REQUEST['rguid'];
}

if (isset($_REQUEST['hlwords'])){
	$_SESSION['hlwords'] = $_REQUEST['hlwords'];
}

if (!$sprtHst && !isSearchBot() && (isset($_REQUEST['oguid']) || isset($_REQUEST['rguid'])) ) {
	header('HTTP/1.0 301 Moved Permanently');
	$url = getCurPageURLWO()."/businessmodel.php";
	header("Location: ".$url);
	ob_end_flush();
	exit;
}

$rguid = null;
$oguid = null;
$forumid = isset($_REQUEST['forumid']) ? $_REQUEST['forumid'] : null;
$hlw = null;
$size = 0;

if (isset($_REQUEST['page']) && $_REQUEST['page'] == "last"){
	unset($_SESSION['page'.$_REQUEST['oguid']]);
}

if (isset($_SESSION['oguid']) ){
	$oguid = $_SESSION['oguid'];
	unset($_SESSION['oguid']);
}

if (isset($_SESSION['rguid'])){
	$rguid = $_SESSION['rguid'];
	unset($_SESSION['rguid']);
}

if (isset($_SESSION['hlwords'])){
	$hlw = $_SESSION['hlwords'];
	unset($_SESSION['hlwords']);
} else {
	$hlw = '';
}

unset($_SESSION['NotSupportHistory']);

$cn = db_connect();
$url = getCurPageURL();
$urlWO = getCurPageURLWO();

$contlng = NULL;
$contlngid = NULL;
$usr_arr = GetUserIDs();

if (getSetting('portal','useRights',0) == 1){
  $contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
  $contlngid = $_SESSION['user_idlanguagecontent'];
} else {
	$contlng = 'lang='.db_getDefaultLangShortName($cn);
	$contlngid = db_getDefaultLangID($cn);//$_SESSION['user_idlanguageinterface'];
}
$lngParam = ( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'].'&' : '');

$objectName = db_getObjectName($cn, $oguid, $contlngid);
$reportName = '';
if ($oguid !== $rguid) {
	$reportName = db_getReportName($cn, $rguid, $contlngid);
}

$skbranch = db_getMainSKBranch($cn);
$idbranch = db_getMainIDBranch($cn);	

rememberGuidsInSession();
header('HTTP/1.0 200 Ok');
session_write_close();

if(db_isObjectHaveSource($cn, $oguid, $skbranch)) { //71970
  $scr_o = db_GetObjectSource($cn, $oguid, $skbranch);
  header("Location: ".$urlWO."/businessmodel.php?oguid=".$scr_o.( isset($_REQUEST['rguid']) ? '&rguid='.$_REQUEST['rguid'] : '').( isset($_REQUEST['lang']) ? '&lang='.$_REQUEST['lang'] : ''));
  ob_end_flush();
  exit;
}

function generateReportContent($cn, $oguid, $rguid, $contlngid, $skbranch){
	$flroot = getSetting('storage','fileroot',realpath(dirname(__FILE__)).'/data/');
	$idbranch = db_getMainIDBranch($cn);
	$usr_arr = GetUserIDs();
	
	if (!($oguid === null)){
		$_url = getCurPageURLWO()."/businessmodel.php?".( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : '');
		$_trSt = db_getReportsToObject($cn, $oguid, $usr_arr, $contlngid);
		$_sl = (!($rguid === null )) ? $rguid : '' ;
		for($i=0; $i<sizeof($_trSt); $i++){
			echo '<a href="'.$_url.'&oguid='.urlencode($oguid).'&rguid='.urlencode($_trSt[$i]['r_guid']).'" >'.$_trSt[$i]['r_name'].'</a>';
		}
	}

	if (is_readable(realpath(dirname(__FILE__)).'/include/strip_tags_smart.inc')) {
		include_once(realpath(dirname(__FILE__)).'/include/strip_tags_smart.inc');
		if (db_isLanguageValidByID($cn, $contlngid)){
			$lang_short = db_getLanguageShortByID($cn, $contlngid);
		} else {
			$lang_short = 'falseLang';
		}
		$fs_fname = nameReportWithBranchAndLanguage($flroot, $oguid, $rguid, $lang_short, $idbranch);

		if (strlen($oguid) > 0 && strlen($rguid) > 0 && is_readable($fs_fname) && db_isReportNotExpire($cn, $oguid, $rguid, $contlngid, $skbranch)){
			$fhr = fopen($fs_fname,  'r');
			$fs_cntnt = "";
      $i_guid = '';
			$patern = '';
			$lpos = 0;
			$fpos = 0;
			$dpos = 0;
			$rpos = 0;
			$elem = null;
			$title = '';
			/*proxy for imagies*/
			$img_ext = array('.jpeg','.jpg','.gif','.png','.bmp','.ico','.tiff');
			try {
				while (!feof($fhr)) {
						$buff = fgets($fhr);
						/*proxy for imagies*/
						if(preg_match("/src=[^1]data/is", $buff) && preg_match("/(".implode('|', $img_ext).")/is", $buff)){
							$imlpos = strpos($buff, 'src=');
							$imfpos = strpos($buff, '.files');
							$imglink= 'img.php?'.( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'].'&' : '').'dboguid='.urlencode($oguid).'&oguid='.urlencode($oguid).'&rguid='.urlencode($rguid).'&name=';
							$newbuff = substr($buff, 0, $imlpos + 5 /* 5 is length of 'src="' */ ).$imglink.substr($buff, $imfpos + 7 /* 7 is length of '.files/' */ );
							$buff = $newbuff;
						}
						/*proxy for imagies*/
						$lpos = strpos($buff, '<bsportal:report');
						$fpos = strpos($buff, '<bsportal:file');
						if ( $lpos === false && $fpos === false) {
							$fs_cntnt = $fs_cntnt.$buff;
						} else if (!($lpos === false )) {
							$fs_cntnt = $fs_cntnt.substr($buff, 0, $lpos);
							$rpos = strpos($buff, '</bsportal:report>', $lpos + 16); // slide from start tag <bsportal:report
							$link = str_replace('&', '&amp;', substr($buff, $lpos, $rpos - $lpos + 18) );
							$patern = substr($link, 0, 4);
							$xmlstr = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'.str_replace('bsportal:report', 'bsrep', $link);
							$xml = simplexml_load_string($xmlstr);
							$title = $xml;
							$elem = $xml->xpath('//bsrep');
							$i_guid = $oguid ;
							if (isset($elem[0]["oguid"])) {
								$i_guid = $elem[0]["oguid"];
							}
							$i_rguid = '';
							if ( isset ($elem[0]["rguid"])){
								$i_rguid = $elem[0]["rguid"];
							}
							if (strpos($link, 'coords="') === false){
									$fs_cntnt = $fs_cntnt.'<portal:a href="';
									$fs_cntnt = $fs_cntnt.getCurPageSubFolders().'/businessmodel.php?oguid='.$i_guid.($i_rguid == '' ? '' : '&rguid='.$i_rguid);
									$fs_cntnt = $fs_cntnt.'">';
									$fs_cntnt = $fs_cntnt.$title;
									$fs_cntnt = $fs_cntnt.'</portal:a>';

							} else {
									$fs_cntnt = $fs_cntnt.'<portal:area shape="rect" coords="';
									$fs_cntnt = $fs_cntnt.$elem[0]["coords"].'" ';
									$fs_cntnt = $fs_cntnt.' href="';
									$fs_cntnt = $fs_cntnt.getCurPageSubFolders().'/businessmodel.php?oguid='.$i_guid.($i_rguid == '' ? '' : '&rguid='.$i_rguid);
									$fs_cntnt = $fs_cntnt.'" alt=" ';
									$fs_cntnt = $fs_cntnt.$title;
									$fs_cntnt = $fs_cntnt.'" /> ';
							}
							$fs_cntnt = $fs_cntnt.substr($buff, $rpos + 18);
						} else if (!($fpos === false )) {
							$fs_cntnt = $fs_cntnt.substr($buff, 0, $lpos);
							$rpos = strpos($buff, '</bsportal:file>', $lpos + 14); // slide from start tag <bsportal:file
							$link = substr($buff, $fpos, $rpos - $fpos + 16);
							$patern = substr($link, 0, 4);
							$xmlstr = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'.str_replace('bsportal:file', 'bsfile', $link);
							$xml = simplexml_load_string($xmlstr);
							$title = $xml;
							$elem = $xml->xpath('//bsfile');
							$i_guid = $elem[0]["oguid"];
							$i_file = urldecode($elem[0]["file"]);
							$fs_cntnt = $fs_cntnt.'<portal:a href="';
							$fs_cntnt = $fs_cntnt.getCurPageSubFolders().'/downloadreportfile.php?'.( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'].'&' : '').'oguid='.$i_guid.'&file='.urlencode($i_file);
							$fs_cntnt = $fs_cntnt.'">';
							$fs_cntnt = $fs_cntnt.$title;
							$fs_cntnt = $fs_cntnt.'</portal:a>';
						}
				}
			} catch (Exception $e) {
				logmessage ( $e->getMessage() );
			}
			fclose($fhr);

			$trans = array(";" => "", "'" => "", "&quot" => '"',  "&nbsp" => "", " 1 " => "", " 2 " => "", " 3 " => "", " 4 " => "", " 5 " => "", " 6 " => "", " 7 " => "", " 8 " => "", " 9 " => "");
			$fs_cntnt = strip_tags_smart(
						$fs_cntnt,
						array('bsportal:report','bsportal:file','portal:a', 'portal:area', 'img'),
						true,
						array('script', 'style', 'map', 'iframe', 'frameset', 'object', 'applet', 'comment', 'button', 'textarea', 'select'),
						array('p', 'td', 'th', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'form', 'title', 'pre')
				);
			$fs_cntnt = strtr($fs_cntnt, $trans);
			$fs_cntnt = str_replace('<portal:a', '<a', str_replace('</portal:a', '</a', $fs_cntnt));
			echo $fs_cntnt;
		}
	}
}

$title = renderTitle($objectName, $reportName);
?>
<!doctype html>
<html>
<head>
	<title><?php echo $title;?></title>
	<? 
		renderCommonMeta($title); 
		renderCommonCSS(); 
	?>
	<link rel="stylesheet" href='css/ui-lightness/jquery-ui-1.8.20.custom.css' />
</head>
<body>
	<?php renderModalHourGlassDiv();?>
	<div id="container" class="layout-resizing-hook">
	<?php renderLoginBlock(); ?>
	<div id="main" role="main" class="ui-layout-center">
		<?php renderMainMenu(); ?>
		<section id="box-tree" class="pane ui-layout-west">
			<header class="clearfix header-hide-overflow">
				<h1><nobr><?php getResource("field.navigator");/* echo ' - '.db_getBranchName($cn,$skbranch,$contlngid);*/?></nobr></h1>
			</header>

			<div id="box-tree-int" class="content">
			<div id="sidetree">
			<div class="treeheader">&nbsp;</div>
			<ul id="mixed">

<?php
$tr_arr = array();
if (!($oguid === null)){
	if (!db_isObjectExits($cn, $oguid, $skbranch)) {
		//60116, 60115
		if (isset($_REQUEST['isretlink']) && $_REQUEST['isretlink'] == 1) {
			header("Location: ".$urlWO."/businessmodel.php?".( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : ''));
		} else {
			header("Location: ".$urlWO."/pagenotfound.php?url=".getCurPageWithEncodeParams());
		}
		ob_end_flush();
		$oguid = null;
		exit;
	} else if (!db_getUserRightsToObject($cn, $usr_arr, $oguid)) {
		if (isset($_REQUEST['isretlink']) && $_REQUEST['isretlink'] == 1) {
			header("Location: ".$urlWO."/businessmodel.php?".( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : ''));
		} else {
			header("Location: ".$urlWO."/notenoughrights.php?url=".getCurPageWithEncodeParams());
		}
		ob_end_flush();
		$oguid = null;
		exit;
	} else {
		if (isset($_REQUEST['isretlink']) && $_REQUEST['isretlink'] == 1) {
			//53332 
			if ($rguid !== NULL && !db_isObjectsReportsExits($cn, $oguid, $rguid, $contlngid, $skbranch)){
				header("Location: ".$urlWO."/businessmodel.php?oguid=".$oguid.( isset($_REQUEST['lang']) ? '&lang='.$_REQUEST['lang'] : ''));
				ob_end_flush();
				exit;
			}
			//remove isretlink param
			header("Location: ".urlReplaceParam(getCurPageURL(), isretlink, NULL));
			ob_end_flush();
			exit;
		}

		$idobj = 0;
 		$idobj = db_getIDObjectByGuid($cn, $oguid);
 		if ( $idobj == 0 ) {
			 getResource("message.notEnoughRights");
			 echo "  ".$oguid;
 			exit;
 		}

 		$tr_arr = db_getPreparedObjectTreetoUser($cn, $idobj, $usr_arr, $contlngid);
		$roots = db_getRootObjectTreeFromPreparetTree($cn);

		$size = sizeof($tr_arr);
		$tree = new Tree();
		for($i=0; $i<$size; $i++){
			if (in_array($tr_arr[$i]['idobject'], $roots)){
				$tree->addItem($tr_arr[$i]['idobject'], 0, $tr_arr[$i]);
			} else {
				$tree->addItem($tr_arr[$i]['idobject'], $tr_arr[$i]['parent_idobject'], $tr_arr[$i]);
			}
		}
		echo $tree->createHtml(0);
 		unset($tr_arr);
 		unset($roots);
 		unset($tree);
	}
} else {
	$tr_arr = db_getObjectTreetoUser($cn, 0, $usr_arr, $contlngid);
	foreach ($tr_arr as $node) {
		echo '<li id="'.$node['idobject'].'" name="'.$node['o_guid'].'" class="hasChildren"><nobr><span><img src="'.$urlWO.'/'.getImgIcon($node['o_icon']).'" class="navigation_image"/><a id="treeLink" class="treeLink" href="businessmodel.php?oguid='.urlencode($node['o_guid']).'" o_guid="'.$node['o_guid'].'" title="'.htmlspecialchars(prepareTextToTree($node['o_name'])).'" >'.htmlspecialchars(prepareTextToTree($node['o_name'])).'</a></span></nobr>';
		if (($node['o_iright'] - $node['o_ileft']) != 1 ){
			echo '<ul>';
			echo '	<li><span class="placeholder">&nbsp;</span></li>';
			echo '</ul>';
		}
		echo '</li>';
	}
}
?>
</ul>
</div>
</div>
	   </section>
<?php if (getSetting('portal','useRights',0) == 1){?>
	   <section id="box-layout-east" class="pane ui-layout-east" style="display: none;">
			<header class="clearfix">
				<h1 id="box-layout-east-title" name="box-layout-east-title"><?php getResource("button.showforum");?></h1>
			</header>
			<div id="box-layout-east-container" name="box-layout-east-container" class="ui-layout-east">
				<img src="img/hourglass.png" class="img-glass-hour-center">
			</div>
		</section>	   
		<section id="box-frame" class="pane ui-layout-center box-frame-wide">
<?php } else {?>
	<section id="box-frame" class="pane ui-layout-center box-frame-padding">
<?php } ?>
			<header id="header-pane-north" class="pane ui-layout-north clearfix">
				<div id="box-frame-header-left">
					<h1 id="repotlabel" class="box-frame-header-left-h1"><?php getResource("field.Report");?></h1>
					<select id="cmreports" name="cmreports" onchange="cmbxChange(this.value)">
<?php
if (!($oguid === null)){
	$trSt = db_getReportsToObject($cn, $oguid, $usr_arr, $contlngid);
	$size = sizeof($trSt);
	if (($rguid !== null && !db_isObjectsReportsExits($cn, $oguid, $rguid, $contlngid, $skbranch)) ||
	db_getUserRightsToObject($cn, $usr_arr, $oguid, $skbranch) === null ||
	($rguid !== null && db_getUserRightsToReport($cn, $usr_arr, $rguid, $oguid, $contlngid, $skbranch) === null )) {
		//60062,63169
		echo '<option style="display: none" value="" selected="selected">';
	} 
	if ($size > 0) {
		//61470
		if ($rguid === null && $size > 0) {
			$rguid = $trSt[0]['r_guid'];
		}
		$sl = (!($rguid === null )) ? $rguid : '' ;
		for($i=0; $i<$size; $i++){
			if ($sl == $trSt[$i]['r_guid'] ) {
				echo '<option value="'.$trSt[$i]['r_guid'].'" selected="selected">';
			} else {
				echo '<option value="'.$trSt[$i]['r_guid'].'">';
			}
				echo $trSt[$i]['r_name'];
			echo '</option> ';
		}
	}
}
?>
					</select>
				</div>
				<div id="box-frame-header-right" class="no-support" style="display:none">
				<?php 
				if ($size == 0) { ?>
					<?php if (getSetting('portal','enableDocButton',1) == 1){?><a class="btn-top btn-top-doc" id="link_doc" name="link_doc" title="<?php getResource('button.doc.hint');?>" href="#"><span>DOC</span></a><?php } if (getSetting('portal','enablePdfButton',1) == 1){?><a class="btn-top btn-top-pdf" id="link_pdf" name="link_pdf" title="<?php getResource('button.pdf.hint');?>" href="#"><span>PDF</span></a><?php } ?><a class="btn-top btn-top-sendem" id="link_mailto" name="link_mailto" title="<?php getResource('button.sendem.hint');?>" href="mailto:?subject=<?php getResource('email.bmsentlink.subject');?>&body=<?php getResource('email.bmsentlink.body');?> <?php  echo urlencode( $urlWO."/businessmodel.php?".$lngParam.(($oguid === null) ? "" : 'oguid='.$oguid.'').( ( $oguid === null && !($rguid === null) ) ? "" : "&").(($rguid === null) ? "" : 'rguid='.$rguid.'') ); ?>"><span><?php getResource("button.byMail");?></span></a><?php if (getSetting('portal','useRights',0) == 1){?><a class="btn-top btn-top-fav" id="addln" name="addln" title="<?php getResource('button.addpersonallink.hint');?>" href="javascript:addPersonalLink()"><span><?php getResource("button.toFavorites");?></span></a><?}?><a class="btn-top btn-top-print" id="link_print" name="link_print" title="<?php getResource('button.print.hint');?>" href="#"><span><?php getResource("button.Print");?></span></a>
				<?php } else { ?>
					<?php if (getSetting('portal','enableDocButton',1) == 1){?><a class="btn-top btn-top-doc" id="link_doc" name="link_doc" title="<?php getResource('button.doc.hint');?>" href="<?php  echo $urlWO."/download.php?".$lngParam.(($oguid === null) ? "" : 'oguid='.$oguid.'').( ( $oguid === null && !($rguid === null) ) ? "" : "&").(($rguid === null) ? "" : 'rguid='.$rguid.'&ext=docx'); ?>" ><span>DOC</span></a><?php } if (getSetting('portal','enablePdfButton',1) == 1){?><a class="btn-top btn-top-pdf" id="link_pdf" name="link_pdf" title="<?php getResource('button.pdf.hint');?>" href="<?php  echo $urlWO."/download.php?".$lngParam.(($oguid === null) ? "" : 'oguid='.$oguid.'').( ( $oguid === null && !($rguid === null) ) ? "" : "&").(($rguid === null) ? "" : 'rguid='.$rguid.'&ext=pdf'); ?>" ><span>PDF</span></a><?php } ?><a class="btn-top btn-top-sendem" id="link_mailto" name="link_mailto" title="<?php getResource('button.sendem.hint');?>" href="mailto:?subject=<?php getResource('email.bmsentlink.subject');?>&body=<?php getResource('email.bmsentlink.body');?> <?php  echo urlencode( $urlWO."/businessmodel.php?".(($oguid === null) ? "" : 'oguid='.$oguid.'').( ( $oguid === null && !($rguid === null) ) ? "" : "&").(($rguid === null) ? "" : 'rguid='.$rguid.'') ); ?>" ><span><?php getResource("button.byMail");?></span></a><?php if (getSetting('portal','useRights',0) == 1){?><a class="btn-top btn-top-fav" id="addln" name="addln" title="<?php getResource('button.addpersonallink.hint');?>" href="javascript:addPersonalLink()" ><span><?php getResource("button.toFavorites");?></span></a><?}?><a class="btn-top btn-top-print" id="link_print" name="link_print" title="<?php getResource('button.print.hint');?>" href="<?php  echo $urlWO."/report.php?".$lngParam.(($oguid === null) ? "" : 'oguid='.$oguid.'').( ( $oguid === null && !($rguid === null) ) ? "" : "&").(($rguid === null) ? "" : 'rguid='.$rguid.'&mode=print'); ?>" ><span><?php getResource("button.Print");?></span></a>
				<?php } ?>

				</div>
			</header>
<?php
	if (getSetting('page','businessmodel.contenttorobot',0) == 1){
		echo('<div id="reportcontent">');
		generateReportContent($cn, $oguid, $rguid, $contlngid, $skbranch);
		echo('</div>');
	}
	renderFooterTemplate();
?>
		</section>
	</div>
</div>

<a href="javascript:void(0)" id="btn-tree-open"><span class="btn-left-open-span"><?php getResource("field.navigator");?></span></a>
<?php if (getSetting('portal','useRights',0) == 1){?>
	<a href="javascript:void(0)" id="btn-discussion-open" class="self-event btn-rigth-first btn-vertical-right-select"  style="display:none;"><span class="btn-right-open-span"><?php getResource("button.showforum");?></span></a>
<? } ?>
<script>

    // cookie to layout
	var oLSize = <?php echo (isset($_COOKIE['layout_west']) ? $_COOKIE['layout_west'] : "200"); ?> ;
  	var wstHide = <?php if ((isset($_COOKIE['layout_west_hide']) && $_COOKIE['layout_west_hide'] == '1') || $ismob) { echo '1'; } else {echo '0';} ?>;
    var oRSize = <?php echo (isset($_COOKIE['layout_east']) ? $_COOKIE['layout_east'] : "400"); ?> ;
   	var eastHide = <?php if (isset($_COOKIE['layout_east_hide']) && $_COOKIE['layout_east_hide'] == '1' && $forumid === null) { echo '1'; } else {echo '0';} ?>;

	// global params
	var isPublication = <?php echo (getSetting('portal','useRights',0) == 0 ?  'true': 'false'); ?>;
	var isMobileMode = <?php echo ($ismob ?  '1': '0'); ?>;
	var gCloseTitle = "<?php getResource('title.close');?>";
	var gOpenTitle = "<?php getResource('title.open');?>";
	var gForumTitle = "<?php getResource('button.showforum');?>";
	var gResizeTitle = "<?php getResource('title.resize');?>";
	var goguid = <?php if ($oguid === null){ echo "null; "; } else { echo '"'.$oguid.'"; '; } ?>
	var grguid = <?php if ($rguid === null){ echo "null; "; } else { echo '"'.$rguid.'"; '; } ?>
	var gforumid = <?php if ($forumid === null){ echo "null; "; } else { echo $forumid.'; '; } ?>
	var titlePrefix = "<?php echo getTitleForSettings();?>";
	var gurl = '';
	var gDeleteLang = false;
	var existUnsavedData = false;
	var gConfirmsavelesValue ="<?php getResource("confirm.savelesValue");?>";
	var mobileViewReport = true; 
</script>

<script src="js/libs/jquery.cookie.js"></script>
<script src="js/libs/jquery.layout.js"></script>
<script src="js/libs/jquery.treeview.js"></script>
<script src="js/libs/jquery.treeview.edit.js"></script>
<script src="js/libs/jquery.treeview.async.js"></script>
<script src="js/libs/jquery.scrollTo.js"></script>
<script src="js/script.js"></script>
<script src="js/framedocload.js"></script>
<script src="js/businessmodel.js"></script>
<?php if (getSetting('portal','useRights',0) == 1){?>
	<script src="js/rightbuttons.js"></script>
	<script src="js/businessmodel.rights.js"></script>
<?php } ?>
<script src="js/tree.js"></script>
<script src="js/a-confirm.js"></script>
<script>

<?php
if  ( (!($oguid === null)) && (!($rguid === null))) {
	echo 'var docName = "'.$urlWO.'/report.php?'.$lngParam.'oguid='.urlencode($oguid).'&rguid='.urlencode($rguid).''.(($hlw != '') ? '&hlwords='.htmlentities(urlencode($hlw)) : '' ).'";';
} else if (!($oguid === null)) {
    if ($size > 0) {
		$rguid = $trSt[0]['r_guid'];
		echo 'var docName = "'.$urlWO.'/report.php?'.$lngParam.'oguid='.urlencode($oguid).'&rguid='.urlencode($rguid).''.(($hlw != '') ? '&hlwords='.htmlentities(urlencode($hlw)) : '' ).'";';
	} else {
		echo 'var docName = "'.$urlWO.'/report.php?'.$lngParam.'oguid='.urlencode($oguid).''.(($hlw != '') ? '&hlwords='.htmlentities(urlencode($hlw)) : '' ).'";';
	}
} else {
	echo 'var docName = "'.$urlWO.'/service/empty.php'.'";';
}
?>

<?php
	if ( $sprtHst && !isSearchBot() ) {
?>
	//	function to redraw tree to new url params
	function redrawTreeToURL() {
	 	var u = new Url;
	 	var o = null;
	 	var r = null;
		if ( u.query["oguid"] ) {
			o = u.query["oguid"];
		}
		if ( u.query["rguid"] ) {
			r = u.query["rguid"];
		}
		if ( o ) {
			postMessage('noreloaddoc!oguid=' + o + ( ( r ) ? '&rguid=' + r : '' ),'*');
		} else {
	    		clearSelectionInTree();
			var cmbx = $('#cmreports');
			$(cmbx).find("option").remove().end();
			setTitle();
	    	}
	}
<?php
	}
?>
	// event on click on tree node
	function clickTree(oguid){
		if (existUnsavedData && !confirm(gConfirmsavelesValue))
			return;
		gDeleteLang = true;
		clearSelectionInTree();
		selector = 'li[name="'+oguid+'"]';
		$(selector).css("font-weight", "bold");
		$(selector+' ul').children().css('font-weight', 'normal');
		loadreport(oguid, null);
		setTitle();
	}

	// event on click on tree node with scr_guid
	function clickTreeMessage(oguid, broadcast){
		if (existUnsavedData && !confirm(gConfirmsavelesValue))
			return;
		clearSelectionInTree();
    postMessage("oguid=" + oguid, broadcast)
	}  

	function clearforumpage(){
		$.get( "<?php echo $urlWO; ?>/service/clearforumpage.php", function( ) {});
	}

	// event on load page
	$(document).ready(function(){
		$("#reportcontent").hide();
		$(".treeLink").click(function(e){
		 	e.preventDefault();
			clickTree($(this).attr('o_guid'));
		});
			<?php
				if ( $sprtHst && !isSearchBot() ) {
					echo "	if ( !supportHistoryApi() ) {                               "
						."		document.forms['CheckSupportHistory'].submit();         "
						."	}                                                           ";
				}

				if ($size > 0){
					echo "setcurretnurl(goguid, grguid);";
				}

			?>
		initTrees("<?php  echo $urlWO?>/service/treeStructService.php<?php echo '?'.$contlng ?>");
	<?php
		if (!($oguid === null)){
			echo "$('div#box-tree-int').scrollTo($('li[name=\"".$oguid."\"]').parent().parent());";
			echo "$('li[name=\"".$oguid."\"]').css('font-weight', 'bold');";
			echo "$('li[name=\"".$oguid."\"] ul').children().css('font-weight', 'normal');";
		}
	?>
	});

    // set curretn url
	function setcurretnurl(oguid, rguid){
		if (oguid === null || typeof oguid == 'undefined' || oguid.length == 0){
			$("#link_pdf").attr("href","#");
			$("#link_doc").attr("href","#");
			$("#link_print").attr("target","_self").attr("href","#");
			setTitle();
		} else {
			var root = "<?php echo $urlWO ?>";
			var url = "";
			if (oguid != null || rguid != null) {
				url = url + "?" + ((oguid == null) ? "" : "oguid=" + oguid) +
					((rguid != null) ? "&" : "") +
					((rguid == null) ? "" : "rguid=" + rguid);
			}
			var emailcurl = root + "/businessmodel.php" + url;

			$("#link_mailto").attr("href","mailto:?subject=<?php getResource('email.bmsentlink.subject');?>&body=<?php getResource('email.bmsentlink.body');?> " + encodeURIComponent(emailcurl));

			var lng = ( getUrlParameter('lang') != null ? '&lang=' + getUrlParameter('lang') : ''); 

			var pdfl =  root + "/download.php" + url + lng + "&ext=pdf";
			$("#link_pdf").attr("href",pdfl);
			var docl = root + "/download.php" + url + lng + "&ext=docx";
			$("#link_doc").attr("href",docl);
			var printl = root + "/report.php" + url + lng + "&mode=print";
			$("#link_print").attr("href",printl);
			if (rguid != null) {
				$("#link_print").attr("target","_blank");
			} else {
				$("#link_print").attr("target","_self");
			}
			if (goguid != oguid){
				loadforum(oguid, null);   
			}
			grguid = rguid;
			goguid = oguid;
		}
	}

	// load data to combo box
	function loadcm(oguid, rguid){
		if (oguid != null && typeof oguid !== 'undefined' && oguid.length > 0){
			if (goguid !== oguid) {
				clearforumpage();
			}

			var cmbx = $("#cmreports");
			$(cmbx).removeAttr('selected').val('');

			grguid = null;
			$.ajax({
					url: "<?php  echo $urlWO?>/service/reportListService.php<?php echo '?'.$contlng ?>&oguid=" + encodeURIComponent(oguid) ,
					dataType: "json",
				success: function(response) {
					$(cmbx).find("option").remove().end();
					$.each(response, function() {
						if (grguid == null) {
							grguid = this.guid;
							goguid=(oguid ? oguid : goguid);
							setcurretnurl(goguid, grguid);
						}
						var htmlappend = '<option value="'+this.guid+'" ';
						if ((rguid != null) && (this.guid == rguid)) {
							htmlappend = htmlappend + ' selected="selected" ';
						}
						htmlappend = htmlappend + '>' + this.name.split("&frasr;").join("\\") + '</option>';
						$(cmbx).append( $(htmlappend));
					;});
					if ($('#cmreports').val() == null || $('#cmreports').val() == '') {

						var root = "<?php echo $urlWO ?>";
						var url = "";
							url = url + "?" + ((oguid == null) ? "" : "oguid=" + encodeURIComponent(oguid));
						var curl = root + "/report.php" + url + "&savehtml=1&mode=print";
						var emailcurl = root + "/businessmodel.php" + url;

						$("#link_mailto").attr("href","mailto:?subject=<?php getResource('email.bmsentlink.subject');?>&body=<?php getResource('email.bmsentlink.body');?> " + encodeURIComponent(emailcurl));
						$("#link_pdf").attr("href","#");
						$("#link_doc").attr("href","#");
						$("#link_print").attr("href","#").attr("target","_self");
					}
				}
			});
			if ($('#cmreports').val() == null || $('#cmreports').val() == '') {
				$(cmbx).empty().focus();
				$('#text-search').focus();
			}
		}
	}



	// load report ( if rguid is null takes first report to object )
	function loadreport(oguid, rguid, reloadDoc){
		if (oguid != null && typeof oguid !== 'undefined' && oguid.length > 0){
			// stop reloads to report
			var iframe = document.getElementById("iframe-doc").contentWindow;
			iframe.postMessage("stopInterval", "*");

			reloadDoc = (reloadDoc != null) ? reloadDoc : true ;
			urlp = "<?php  echo $urlWO?>/service/empty.php";
			if ( oguid != null ){
				var params =
					((oguid == null) ? "" : "oguid=" + encodeURIComponent(oguid)) +
					((oguid != null && rguid != null) ? "&" : "") +
					((rguid == null) ? "" : "rguid=" + encodeURIComponent(rguid)) ;

				var urlp = "<?php  echo $urlWO?>/report.php<?php echo '?'.$contlng;?>&" + params;

				if (( oguid != null && oguid != goguid) || ( rguid == null || rguid != grguid) ){
					loadcm(oguid, rguid);
				}

				//remeber bm guids
				var r_url = "<?php  echo $urlWO?>/service/rememberbm.php?" + params;
				$.get(r_url, function (data) {
					var rm_data = data;
				});

			}
			if ( reloadDoc && reloadDoc == true ) {
				loadDoc(urlp);
			}
			setcurretnurl(oguid, rguid);
			setTitle();
		}
	}

	// event on combobox change element
	function cmbxChange(rguid){
		if (rguid != "0"){
			loadreport(goguid, rguid);
		}
   	    setTitle();
	}

	function addPersonalLink(){
		if (goguid == null)
			return;

		var urlp =  "" +
		((goguid == null) ? "" : "oguid=" + goguid) +
		((goguid != null && grguid != null) ? "&" : "") +
		((grguid == null) ? "" : "rguid=" + grguid) ;

		$.ajax({
				url: "<?php  echo $urlWO?>/service/personallinks.php?command=add&" + urlp ,
				success: function(response) {
					alert(response);
			}
		});
	}

	// add event listner to top window
	if (window.addEventListener){
	    window.removeEventListener("message", listener);
	    window.addEventListener("message", listener, false);
	} else {
	    window.detachEvent("onmessage", listener);
	    window.attachEvent("onmessage", listener);
	}

	// function, that call on post message to main browser window
	function listener(event){
		gDeleteLang = true;
		var iframe = document.getElementById("iframe-doc").contentWindow;
		if (event.data != null) {
			if (event.data.indexOf('refreshlinks') >= 0) {
				return;
			}
			if (event.data == 'createunsaveddata') {
				existUnsavedData = true;
				iframe.postMessage('createunsaveddata','*');      
			} else if (event.data == 'unsaveddatawassave') {
				existUnsavedData = false;
				iframe.postMessage('unsaveddatawassave','*');  
			} else if (event.data == 'reload') {
				// logout
				var url = "";
				if (goguid != null || grguid != null) {
					url = url + "?" + ((goguid == null) ? "" : "oguid=" + goguid) +
						((grguid != null) ? "&" : "") +
						((grguid == null) ? "" : "rguid=" + grguid) ;
				}
				var targeturl = "<?php  echo $urlWO?>/login.php?returl=<?php  echo $urlWO?>/businessmodel.php" + url.split("&").join("_@nd_");
				document.location.href = targeturl;
			} else {
				var noreloaddoc = event.data.indexOf('noreloaddoc') >= 0;
				var cmbx = $('#cmreports');
				if (event.data.indexOf('oguid') >= 0) {
					// load object
                    var idx1 = event.data.indexOf('oguid');
                    var idx2 = event.data.indexOf('&');
                    var idx3 = event.data.indexOf('rguid');
					var oguid = "";
					if (idx2 >= 0 ) {
						oguid = event.data.substr(idx1 + 6, idx2 - (idx1 + 6)); // 6 - lehgth of r\oguid
					} else {
						oguid = event.data.substr(idx1 + 6);
					}
                    if (oguid != goguid) {
                    	clearSelectionInTree();
						loadTreeByNode(oguid);
						if (idx3 < 0 ) {
							loadreport(oguid, null, !noreloaddoc);
						} else {
							// load report
							grguid = event.data.substr(idx3 + 6); // 6 - lehgth of r\oguid
							$(cmbx).val(grguid);
							loadreport(oguid, grguid, !noreloaddoc);
						}
					} else if (idx3 >= 0 ){
						// load report
						grguid = event.data.substr(idx3 + 6);
						$(cmbx).val(grguid);
						loadreport(goguid, grguid, !noreloaddoc);

					} else {
						// load report from history
						loadreport(oguid, null, !noreloaddoc);
					}
				} else if (event.data.indexOf('rguid') >= 0 ) {
					// load report ( to support old versions )
					grguid = event.data.substr(event.data.indexOf('rguid') + 6);
					$(cmbx).val(grguid);
					loadreport(goguid, grguid, !noreloaddoc);
                }
			}
		}
	}

	function setTitle(){
		var reportName = "";
		if( $('#cmreports').is(':visible') ) {
			reportName = $("#cmreports option:selected").text();
		}
		var atitle = titlePrefix;
		var selector = 'li[name="'+goguid+'"]';
		var objName = "";
		objName = $(selector).find('a').first().text();
		if (objName && objName.length > 0) {
			atitle = atitle + " " + objName;
		}
		if (objName && reportName && reportName.toString() != objName.toString() && objName.length > 0 && reportName.length > 0) {
			atitle = atitle + " (" + reportName + ")";
		}
		if (atitle) {
			document.title = atitle;
		} else {
			document.title = titlePrefix;
		}
	}

    // build tree structure for node
	function loadTreeByNode(oguid){
		if (oguid != null && typeof oguid !== 'undefined' && oguid.length > 0){
			var tree = document.getElementById("mixed");
			$.ajax({
				url: "<?php  echo $urlWO?>/service/treeExpandService.php<?php echo '?'.$contlng ?>&oguid=" + oguid ,
				dataType: "json",
			success: function(response) {
						$.each(response, function(tree) { $.fn.asyncExpandNodes(tree,this);});
						var selector = 'li[name="'+oguid+'"]';
						$(selector).css("font-weight", "bold");
						$(selector+' ul').children().css('font-weight', 'normal');
						$("div#box-tree-int").scrollTo($(selector).parent().parent());
        			}
			});
		}
	}
	
	// load forum page to object
	function loadforum(oguid, rguid, forumid){
		if (oguid != null && typeof oguid !== 'undefined' && oguid.length > 0){
			var params =
				((oguid == null) ? "" : "oguid=" + encodeURIComponent(oguid)) +
				((oguid != null && rguid != null) ? "&" : "") +
				((rguid == null) ? "" : "rguid=" + encodeURIComponent(rguid));

			var urlf =  "<?php  echo $urlWO?>/forum.php?" + params + ( typeof forumid !== "undefined" && isInteger(forumid) ? "&forumid=" + forumid : "" );
		} else {
			var urlf =  "<?php  echo $urlWO?>/empty.php";
		}
		loadSubDoc(urlf);
	}	
</script>
<script src="js/close-confirm.js"></script>
<?php
	if ( $sprtHst && !isSearchBot() ) {
?>
<form name="CheckSupportHistory" id="CheckSupportHistory" method="post" style="display:none;visibility:hidden;" >
  <input id="NotSupportHistory" type="text" name="NotSupportHistory" value="1" style="display:none;visibility:hidden;" />
</form>
<?php
	}
?>

<?php
	if(!(is_readable(realpath(dirname(__FILE__)).'/templates/languagesbox.template'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/templates/languagesbox.template');
	} else {
		include_once(realpath(dirname(__FILE__)).'/templates/languagesbox.template');
	}
?>

<?php
	if (getSetting('page','businessmodel.noframes',0) == 1){
		echo('<frameset><noframes>');
		generateReportContent($cn, $oguid, $rguid, $contlngid);
		echo('</noframes></frameset>');
	}
	renderFooterTemplate();
?>
</body>
</html>
<?php
db_disconnect($cn);
unset($trSt);
unset($tr_arr);
ob_end_flush();
?>