<?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');
}

$oLSize = '200';
if (isset($_COOKIE['layout_west'])) {
	$oLSize	= $_COOKIE['layout_west'];
}
$oRSize = '400';
if (isset($_COOKIE['layout_east'])) {
	$oRSize	= $_COOKIE['layout_east'];
}


checkUserAndRedirectToLogin();
RedirectToModelAnonymous();

if (!isset($_REQUEST['skpollingobject']) || !isset($_REQUEST['skpolltype']) || !is_numeric($_REQUEST['skpollingobject']) || !is_numeric($_REQUEST['skpolltype'])) {
	RedirectToPageNotFound();
}

$cn = db_connect();
$idbranch = '';
$usr_arr = GetUserIDs();
$skpollingobject = $_REQUEST['skpollingobject'];

$pOStatus = db_getPollObjectStatus($cn, $skpollingobject, $_REQUEST['skpolltype']);
$isuserassigned = db_getSKBranchByUserAnswerValue($cn, $skpollingobject, $_REQUEST['skpolltype'], $usr_arr[0] ) != 0 && $pOStatus == 1;

if (isset($_REQUEST['skbranch'])) {
	$skbranch = $_REQUEST['skbranch'];
	$idbranch = db_getIDBranch($cn, $skbranch );	
} 

if ($idbranch == '' || !db_isBrancheComplite($cn, $skbranch) ) {
	RedirectToPageNotFound();
}

$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'];
}

$rguid = null;
$oguid = null;
$poguids = db_getGuidsByPollingObject($cn, $skpollingobject);
if (is_array($poguids) && sizeof($poguids) > 0 && sizeof($poguids[0]) > 0){
        $pollobjectoguid = $poguids[0]['o_guid'];
        $pollobjectrguid = $poguids[0]['r_guid'];
} else {
        db_disconnect($cn);
		RedirectToPageNotFound();
}
$objecthash = db_getObjectVersionuHashByPollingObject($cn, $skpollingobject);

if  (!isset($_REQUEST['oguid']) || !db_isObjectExits($cn, $_REQUEST['oguid'], $skbranch)) {
	db_disconnect($cn);
	RedirectToPageNotFound();
}
if  (db_getUserRightsToObject($cn, GetUserIDs(), $_REQUEST['oguid'], $skbranch) === null ){
	db_disconnect($cn);
	header("Location: ".getCurPageURLWO()."/notenoughrights.php?url=".getCurPageWithEncodeParams());
	ob_end_flush();
	exit;
}

$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']);

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

$contlng = NULL;
$contlngid = NULL;



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);
}
$lngParam = ( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'].'&' : '');

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

$sourceparams = db_getPollingObjectSource($cn, $skpollingobject);
$idpolltype = db_getIDPollTypeBySK($cn,(isset($_REQUEST['skpolltype']) ? $_REQUEST['skpolltype'] : NULL));
$urlpoll = getCurPageURLWO().'/poll.php?idpolltype='.$idpolltype.(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : (isset($_REQUEST['skbranch']) ? '&skbranch='.$_REQUEST['skbranch'] : ''));
$objectfullname = $objectName.' ('.$reportName.')';
$ismob = (isset($_COOKIE['mobilemode']) && $_COOKIE['mobilemode'] == 1);
header('HTTP/1.0 200 Ok');

$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(strtolower(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME)), FALSE); ?>
			<?php if (isset($_REQUEST['skpollingobject']) ) {?> 
				<section id="box-poll-bread-crumbs" class="clearfix" style="display: none;">
					<div class="inline-float-left">
						<div id="box-poll-bread-crumbs-text" >
						<?php if ($isuserassigned && isset($_REQUEST['idpolltype'])) {?>
							<a href="polls.php"><?php getResource("title.polls");?></a> \ <a id="poll-part-bread-crumbs" href="<?php echo $urlpoll;?>"><?php echo ''.db_getPolltypeName($cn, $idpolltype, $contlngid).': '; if ($sourceparams[0]['source'] === 'skproject') { echo db_getProjectName($cn, $sourceparams[0]['id'], $contlngid);} else { echo db_getBranchName($cn, $sourceparams[0]['id'], $contlngid);} ?></a> \ <a style="display:none;" href="#" oguid="<?php echo $oguid;?>" rguid="<?php echo $rguid;?>" class="selfPollReload box-poll-bread-crumbs-objectfullname-link"> <?php echo $objectfullname;?></a> <span class="box-poll-bread-crumbs-objectfullname-span"> <?php echo $objectfullname;?></span> 
						<?php } else if (!$isuserassigned && isset($_REQUEST['idpolltype'])) { /*Task 63358 show only pollobkect name*/ ?>
							<a href="polls.php"><?php getResource("title.polls");?></a> \ <a id="poll-part-bread-crumbs" href="<?php echo $urlpoll;?>"><?php echo ''.db_getPolltypeName($cn, $idpolltype, $contlngid).': '; if ($sourceparams[0]['source'] === 'skproject') { echo db_getProjectName($cn, $sourceparams[0]['id'], $contlngid);} else { echo db_getBranchName($cn, $sourceparams[0]['id'], $contlngid);} ?></a> 
						<?php } else {?>
							<a href="polls.php"><?php getResource("title.polls");?></a> \ <?php echo db_getBranchName($cn, $skbranch, $contlngid, NULL); ?> \ <?php echo $objectfullname;?> 
						<?php } ?>
						</div>
					</div>
					<div class="float-right font-awesome-color" style="margin-top: 8px;">
					<?php
					if (isset($_REQUEST['filteruniqid']) && isset($_SESSION['pollsfilteredlist'.$_REQUEST['filteruniqid']]) && is_array($_SESSION['pollsfilteredlist'.$_REQUEST['filteruniqid']]) && sizeof($_SESSION['pollsfilteredlist'.$_REQUEST['filteruniqid']]) > 0) {
						$resarr = $_SESSION['pollsfilteredlist'.$_REQUEST['filteruniqid']];
					} else {
						db_getPollObjetcList($cn, (isset($_REQUEST['idpolltype']) ? $_REQUEST['idpolltype'] : NULL), (isset($_REQUEST['skproject']) ? $_REQUEST['skproject'] : NULL),  (isset($_REQUEST['skbranch']) ? $_REQUEST['skbranch'] : NULL), $contlngid, $usr_arr, (isset($_REQUEST['foldergroup']) ? $_REQUEST['foldergroup'] : NULL), (isset($_REQUEST['answers']) ? $_REQUEST['answers'] : NULL) );
						$resarr = array();
						$q_st = "SELECT COUNT(0) as cnt FROM `poll` ";
						$resarr = db_runQueryAndReturnArray($cn,$q_st);
						if ($resarr[0]['cnt'] > 1) {
							$q_st = 'SELECT `skpollingobject`, `skpolltype` , `skbranch` , `o_guid` , `r_guid` , `idobject` , `idreport`  FROM `poll` ORDER BY o_name desc';
							$resarr = db_runQueryAndReturnArray($cn,$q_st);
						}
					}
					session_write_close();
					$size = (is_array($resarr) ? sizeof($resarr) : 0 );
					if ($size > 1) {
						$curentIndexOfPollObject = 0;
						for($i=0; $i<$size; $i++){						
							if ($resarr[ $i ][ "r_guid" ] == $pollobjectrguid && $resarr[ $i ][ "o_guid" ] == $pollobjectoguid && $resarr[ $i ][ "skbranch" ] == $skbranch && $resarr[ $i ][ "skpollingobject" ] == $skpollingobject && $resarr[ $i ][ "skpolltype" ] == (isset($_REQUEST['skpolltype']) ? $_REQUEST['skpolltype'] : '') ){
								$curentIndexOfPollObject = $i;
								break;
							}
						}
						$ulrPONextIndex = ( isset($resarr[$curentIndexOfPollObject+1]) ? $curentIndexOfPollObject + 1 : 0 );	
						$ulrPONext = ($ismob ? $urlWO.'/pollobject.php' : $urlWO.'/service/pollobjectbreadcrumbs.php').'?skpollingobject='.$resarr[ $ulrPONextIndex ][ "skpollingobject" ].'&skpolltype='.$resarr[ $ulrPONextIndex ][ "skpolltype" ].'&skbranch='.$resarr[ $ulrPONextIndex ][ "skbranch" ].'&oguid='.$resarr[ $ulrPONextIndex ][ "o_guid" ].'&rguid='.$resarr[ $ulrPONextIndex ][ "r_guid" ].(isset($_REQUEST['idpolltype']) ? '&idpolltype='.$_REQUEST['idpolltype'] : '').(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : '').'&idbranch='.db_getIDBranch($cn,$resarr[ $ulrPONextIndex ][ "skbranch" ]).(isset($_REQUEST['filteruniqid']) ? '&filteruniqid='.$_REQUEST['filteruniqid'] : '');
						$ulrPOPrevIndex = ( isset($resarr[$curentIndexOfPollObject-1]) ? $curentIndexOfPollObject - 1 : $size - 1 );	
						$ulrPOPrev = ($ismob ? $urlWO.'/pollobject.php' : $urlWO.'/service/pollobjectbreadcrumbs.php').'?skpollingobject='.$resarr[ $ulrPOPrevIndex ][ "skpollingobject" ].'&skpolltype='.$resarr[ $ulrPOPrevIndex ][ "skpolltype" ].'&skbranch='.$resarr[ $ulrPOPrevIndex ][ "skbranch" ].'&oguid='.$resarr[ $ulrPOPrevIndex ][ "o_guid" ].'&rguid='.$resarr[ $ulrPOPrevIndex ][ "r_guid" ].(isset($_REQUEST['idpolltype']) ? '&idpolltype='.$_REQUEST['idpolltype'] : '').(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : '').'&idbranch='.db_getIDBranch($cn,$resarr[ $ulrPOPrevIndex ][ "skbranch" ]).(isset($_REQUEST['filteruniqid']) ? '&filteruniqid='.$_REQUEST['filteruniqid'] : '');
					?>						
					<a class="poll-bread-crumbs-arrow-link" href="<?php echo $ulrPOPrev;?>"><i class="fas fa-arrow-up fa-lg"></i></a><a class="poll-bread-crumbs-arrow-link" style="padding-left: 10px;" href="<?php echo $ulrPONext;?>"><i class="fas fa-arrow-down fa-lg"></i></a>
					<?php
					}
					?>
					</div>
				</section>
			<?}?>
		</section>
		
		<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>

<?php
$tr_arr = array();
if (!($oguid === null)){
	if (!db_isObjectExits($cn, $oguid, $skbranch)) {
		//60116, 60115
		RedirectToPageNotFound();
	} else if ( !( db_getUserRightsToObject($cn, GetUserIDs(), $oguid, $skbranch) )) {
		header("Location: ".$urlWO."/notenoughrights.php?url=".getCurPageWithEncodeParams());
		ob_end_flush();
		$oguid = null;
		exit;
	} else {
		if (isset($_REQUEST['isretlink']) && $_REQUEST['isretlink'] == 1) {
			//remove isretlink param
			header("Location: ".urlReplaceParam(getCurPageURL(), isretlink, NULL));
			ob_end_flush();
			exit;
		}
		$idobj = 0;
 		$idobj = db_getIDObjectByGuid($cn, $oguid, $skbranch );
 		if ( $idobj == 0 ) {
			RedirectToPageNotFound();
		}
	}
} else {
	RedirectToPageNotFound();
}
?>
</section>
		
		<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 if ($isuserassigned && isset($_REQUEST['idpolltype'])) { getResource("title.review"); } else { getResource("button.showforumpoll");} ;?></h1>
			</header>
			<div id="box-layout-east-container" name="box-layout-east-container" class="ui-layout-east">
				<img id="img-box-layout-east-hourglass" src="img/hourglass.png" class="img-glass-hour-center">
			</div>
		</section>

		<section id="box-frame" class="pane ui-layout-center box-frame-wide">
			<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)){
	if (!db_isObjectsReportsExits($cn, $oguid, $rguid, $contlngid, $skbranch) ||
	db_getUserRightsToObject($cn, $userids, $oguid, $skbranch) === null ||
	db_getUserRightsToReport($cn, $userids, $rguid, $oguid, $contlngid, $skbranch) === null ) {//STU язык нужен по сигнатуре
		//60062,63169
		echo '<option style="display: none" value="" selected="selected">';
	} 
	$trSt = db_getReportsToObject($cn, $oguid, GetUserIDs(), $contlngid, $skbranch);
	$size = (is_array($trSt) ? sizeof($trSt) : 0 );
	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" style="display:none" >

				<?php 
				if ($size == 0) { ?>
					<?php if (getSetting('portal','enableDocButton',1) == 1){?><a class="self-event 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="self-event 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="self-event 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-fas" id="addln" name="addln" title="<?php getResource('button.openInBusinessModel.hint');?>" href="javascript:openInBusinessModel()"><i class="fas fa-external-link-alt"></i></a><?}?><a class="self-event 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="self-event 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="self-event 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="self-event 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><a class="btn-top btn-top-openinmodel" id="btn-top-openinmodel" name="btn-top-openinmodel" title="<?php getResource('button.openInBusinessModel.hint');?>" href="#" ><span><?php getResource("button.openInBusinessModel.hint");?></span></a><a class="self-event 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
	renderFooterTemplate();
?>
		</section>
	</div>
</div>

<?php if ($isuserassigned && isset($_REQUEST['idpolltype'])) {
	$cssClassReview = (isset($_REQUEST['forumid']) ? 'btn-vertical-right-unselect' : 'btn-vertical-right-select');
	$cssClassDiscussion = (!isset($_REQUEST['forumid']) ? 'btn-vertical-right-unselect' : 'btn-vertical-right-select');
	?> 
	<a href="javascript:void(0)" id="btn-review-open" class="self-event btn-rigth-first <?php echo $cssClassReview;?>" style="display:none;"><span class="btn-right-open-span"><?php getResource("title.review.btn");?></span></a>
	<a href="javascript:void(0)" id="btn-discussion-open" class="self-event btn-rigth-second <?php echo $cssClassDiscussion;?>"  style="display:none;"><span class="btn-right-open-span"><?php getResource("button.showforum");?></span></a>
<?php } else {?>
	<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>
<?php } ?>

<script>

    // cookie to layout
   	var oLSize = <?php echo $oLSize; ?> ;
   	var oRSize = <?php echo $oRSize; ?> ;
   	var eastHide = <?php if (isset($_COOKIE['pollobject_layout_east_hide']) && $_COOKIE['pollobject_layout_east_hide'] == '1' && $forumid === null) { echo '1'; } else {echo '0';} ?>;

	// global params
	var isMobileMode = <?php echo ($ismob ?  '1': '0'); ?>;
	var mobileViewReport = true; 
	var gSKBranch = "<?php echo $skbranch;?>";
	var gForumTitle = "<?php getResource('button.showforumpoll');?>";
	var gReviewTitle = "<?php getResource('title.review');?>";
	var gCloseTitle = "<?php getResource('title.close');?>";
	var gOpenTitle = "<?php getResource('title.open');?>";
	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 poll_goguid = goguid;
	var poll_grguid = grguid;
	var titlePrefix = "<?php echo getTitleForSettings();?>";
	var gurl = '';
	var gDeleteLang = false;

	var existUnsavedData = false;
	var gConfirmsavelesValue ="<?php getResource("confirm.savelesValue");?>";

	var gIDbranch = "<?php echo $idbranch;?>";
	var gSKbranch = <?php echo $skbranch;?>;
	var gSKpollingobjectUrlPart = "<?php echo 'skpollingobject='.$_REQUEST['skpollingobject'].'&skpolltype='.$_REQUEST['skpolltype'];?>";

</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/a-confirm.js"></script>
<script>

<?php
if  ( (!($oguid === null)) && (!($rguid === null))) {
	echo 'var docName = "'.$urlWO.'/report.php?" + gSKpollingobjectUrlPart + "&safeLinks=true&'.$lngParam.'oguid='.urlencode($oguid).'&rguid='.urlencode($rguid).(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : (isset($_REQUEST['skbranch']) ? '&skbranch='.$_REQUEST['skbranch'] : '')).'&idbranch="+gIDbranch+"'.(isset($_REQUEST['idpolltype']) ? '&idpolltype='.$_REQUEST['idpolltype'] : '').(($hlw != '') ? '&hlwords='.htmlentities(urlencode($hlw)) : '' ).'";';
} else if (!($oguid === null)) {
    if ($size > 0) {
		$rguid = isset($trSt) ? $trSt[0]['r_guid'] : "";
		echo 'var docName = "'.$urlWO.'/report.php?" + gSKpollingobjectUrlPart + "&safeLinks=true&'.$lngParam.'oguid='.urlencode($oguid).'&rguid='.urlencode($rguid).(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : (isset($_REQUEST['skbranch']) ? '&skbranch='.$_REQUEST['skbranch'] : '')).'&idbranch="+gIDbranch+"'.(isset($_REQUEST['idpolltype']) ? '&idpolltype='.$_REQUEST['idpolltype'] : '').(($hlw != '') ? '&hlwords='.htmlentities(urlencode($hlw)) : '' ).'";';
	} else {
		echo 'var docName = "'.$urlWO.'/report.php?" + gSKpollingobjectUrlPart + "&safeLinks=true&'.$lngParam.'oguid='.urlencode($oguid).(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : (isset($_REQUEST['skbranch']) ? '&skbranch='.$_REQUEST['skbranch'] : '')).'&idbranch="+gIDbranch+"'.(($hlw != '') ? '&hlwords='.(isset($_REQUEST['idpolltype']) ? '&idpolltype='.$_REQUEST['idpolltype'] : '').htmlentities(urlencode($hlw)) : '' ).'";';
	}
} else {
	echo 'var docName = "'.$urlWO.'/service/empty.php'.'";';
}
?>
	// отключены по требованию 5.1 [Upd2 06.04.2020]Его не должно выкидывать из опроса (63456) 
	/*
	window.setInterval(checkObjectHash, 3000);
	window.setInterval(checkPollObjectStatus, 5000);
	*/
	function clearforumpage(){
		$.get( "<?php echo $urlWO; ?>/service/clearforumpage.php", function( ) {});
	}

	// event on load page
	$(document).ready(function(){
		checkIsObjectExistsInBusinessModel();
		clearforumpage();
		$("#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);";
				}

			?>
		<?php if ($isuserassigned && $forumid === null && isset($_REQUEST['idpolltype'])) {?> 
			loadreview();
		<?php } else {   ?>
			$( "#btn-discussion-open" ).click();
			loadforum();
		<?php } ?>		
	<?php
		if (!($oguid === null)){
			echo "$('div#box-tree-int').scrollTo('li[name=\"".$oguid."\"]');";
			echo "$('li[name=\"".$oguid."\"]').css('fontWeight', 'bold');";
			echo "$('li[name=\"".$oguid."\"] ul').children().css('font-weight', 'normal');";
		}
	?>
	});

	<?php if (!$ismob) { ?>
		function initPollBreadCrumbsArrowLinks(){
			$('.poll-bread-crumbs-arrow-link').unbind('click');
			$('.selfPollReload').click(function(e){
				var oguid = $(this).attr('oguid');
				var rguid = $(this).attr('rguid');
				loadreport(oguid, rguid);
			});

			$('.poll-bread-crumbs-arrow-link').click(function(e){
				clearforumpage();
				e.stopPropagation();
				e.preventDefault();
				existUnsavedData = (existUnsavedData ? !confirm(gConfirmsavelesValue) : existUnsavedData);
				if (!existUnsavedData){
					ShowGlassWindow(true);
					var lurl = $(this).attr("href");

					gIDbranch = getUrlParameter("idbranch", lurl);
					gSKbranch = getUrlParameter("skbranch", lurl);
					gSKpollingobjectUrlPart = "skpollingobject=" + getUrlParameter("skpollingobject", lurl) + "&skpolltype=" + getUrlParameter("skpolltype", lurl);
					poll_goguid = getUrlParameter("oguid", lurl);
					poll_grguid = getUrlParameter("rguid", lurl)
					loadreport(poll_goguid, poll_grguid);
					if($('#btn-discussion-open').hasClass('btn-vertical-right-select')){
						loadforum(poll_goguid, poll_grguid);
					}
					if($('#btn-review-open').hasClass('btn-vertical-right-select')){
						loadreview();							
					}
					if (supportHistoryApi()) {
						var u = new Url;
			            u.query.idbranch = getUrlParameter("idbranch", lurl);
			            u.query.skbranch = getUrlParameter("skbranch", lurl);
			            u.query.skpollingobject = getUrlParameter("skpollingobject", lurl);
						u.query.skpolltype = getUrlParameter("skpolltype", lurl);
			            u.query.idpollingobject = getUrlParameter("idpollingobject", lurl);
						u.query.idpolltype = getUrlParameter("idpolltype", lurl);
			            u.query.oguid = getUrlParameter("oguid", lurl);
						u.query.rguid = getUrlParameter("rguid", lurl);
						delete u.query["forumid"]
						history.replaceState(null, '', u);
					}

					$.ajax({
						type: "GET",
						url: lurl,
						dataType: "html",
							success: function( data ) {
							$( "#box-poll-bread-crumbs" ).html( data );
							initPollBreadCrumbsArrowLinks();
						},
						error: function() {
							document.location.reload(true);
						}
						});				
				}
			});
		} 

		$(document).ready(function(){
			initPollBreadCrumbsArrowLinks();
		});

	<?php } ?>		

    // 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);
			}
			url = url + "&skbranch=" + gSKBranch;

			var emailcurl = root + "/pollobject.php" + url + "&" + gSKpollingobjectUrlPart;

			$("#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");
			}
			grguid = rguid;
			goguid = oguid;
		}
	}

	// load data to combo box
	function loadcm(oguid, rguid){
		if (oguid != null && typeof oguid !== 'undefined' && oguid.length > 0){
			var cmbx = $("#cmreports");
			$(cmbx).removeAttr('selected').val('');

			grguid = null;
			$.ajax({
					url: "<?php  echo $urlWO?>/service/reportListService.php<?php echo '?'.$contlng.'&idbranch='.$idbranch; ?>&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));
							url = url + "&skbranch=" + gSKBranch;
						var curl = root + "/report.php" + url + "&savehtml=1&mode=print";
						var emailcurl = root + "/pollobject.php" + url + "&" + gSKpollingobjectUrlPart;
						$("#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){
			checkIsObjectExistsInBusinessModel();
			reloadDoc = (typeof reloadDoc !== 'undefined' && 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.'&safeLinks=true';?>" + '&idbranch=' + gIDbranch + "&" + gSKpollingobjectUrlPart + "&" + params;

				if (( oguid != null && oguid != goguid) || ( rguid == null || rguid != grguid) ){
					loadcm(oguid, rguid);
				}
			}
			if ( reloadDoc && reloadDoc == true ) {
				loadDoc(urlp);
			}
			setcurretnurl(oguid, rguid);
			setTitle();
			if($('.box-poll-bread-crumbs-objectfullname-link').attr('oguid') != oguid || $('.box-poll-bread-crumbs-objectfullname-link').attr('rguid') != rguid){
				$('.box-poll-bread-crumbs-objectfullname-link').show();
				$('.box-poll-bread-crumbs-objectfullname-span').hide();
			} else {
				$('.box-poll-bread-crumbs-objectfullname-link').hide();
				$('.box-poll-bread-crumbs-objectfullname-span').show();
			}
		}
	}

	// load forum page to object
	function loadforum(oguid, rguid){
		if (oguid != null && typeof oguid !== 'undefined' && oguid.length > 0){
			oguid = (typeof oguid !== 'undefined' && oguid != null) ? oguid : poll_goguid ;
			rguid = (typeof rguid !== 'undefined' && rguid != null) ? rguid : poll_grguid ;
			urlf =  "<?php  echo $urlWO.'/forum.php?" + gSKpollingobjectUrlPart + "&idbranch=" + gIDbranch + "&skbranch=" + gSKbranch + "&oguid=" + oguid + "&rguid=" + rguid + "'.(!($forumid === null) ? '&forumid='.$forumid : '' );?>";
			loadSubDoc(urlf);
		}
	}

	// load review page to object
	function loadreview(){
		urlf =  "<?php  echo $urlWO;?>/pollobjectanswer.php?" + gSKpollingobjectUrlPart + "&idbranch=" + gIDbranch + ".&idpolltype=" + getUrlParameter("idpolltype");
		loadSubDoc(urlf);
	}

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

	function checkIsObjectExistsInBusinessModel(){
		$("#btn-top-openinmodel").hide();
		if (goguid == null){
			$("#btn-top-openinmodel").hide();
		} else {
			$.ajax({
			url: "<?php echo $urlWO.'/service/checkIsObjectExistsInBusinessModel.php?oguid='?>" + goguid,
			success: function(response) {
					if (response.length > 0) {
						$("#btn-top-openinmodel").show();
						//64664
						var urlp =  "" + ((goguid == null) ? "" : "oguid=" + goguid);
						var url = "<?php  echo $urlWO.'/businessmodel.php?';?>" + urlp;
						$("#btn-top-openinmodel").attr("href", url);
					} else {
						$("#btn-top-openinmodel").hide();
					}
				}
			});
		}
	}

	function openInBusinessModel(){
		if (goguid == null)
			return;
				
		if (existUnsavedData && !confirm(gConfirmsavelesValue))
			return;

		var urlp =  "" + ((goguid == null) ? "" : "oguid=" + goguid);
		var url = "<?php  echo $urlWO.'/businessmodel.php?';?>" + urlp;
		window.location.href = url;
	}

	// 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;
		var iframesubdoc = document.getElementById("iframe-sub-doc").contentWindow;

		if (event.data != null) {
			if (event.data.indexOf('refreshlinks') >= 0) {
				//67802 IE Bug workarround
				var u_frame = new Url(event.data.substring(12));
				var voguid;
				var vrguid;
				
		        if (u_frame.query["oguid"]) {
					voguid = u_frame.query["oguid"];
				} else {
					voguid = null;
				}
				if (u_frame.query["rguid"]) {
					vrguid = u_frame.query["rguid"];
				} else {
					vrguid = null;
				}
				if(goguid !== voguid || grguid !== vrguid){
					loadcm(voguid, vrguid);
				} 
				return;
			}
			if (event.data == 'refreshmenucount') {
				if (typeof refreshMainMenuPollsCount === 'function') 
					refreshMainMenuPollsCount();
			}
			else if (event.data == 'createunsaveddata') {
				existUnsavedData = true;
				iframe.postMessage('createunsaveddata','*');    
				iframesubdoc.postMessage('createunsaveddata','*');    
			} else if (event.data == 'unsaveddatawassave') {
				existUnsavedData = false;
				iframe.postMessage('unsaveddatawassave','*');  
				iframesubdoc.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) {
						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 = '#poll-part-bread-crumbs';
		var objName = "";
		objName = $(selector).text();
		if (objName && objName.length > 0) {
			atitle = atitle + " " + objName;
		}
		if (atitle) {
			document.title = atitle;
		} else {
			document.title = titlePrefix;
		}
	}


</script>
<script src="js/clamp.js"></script>
<script src="js/pollobject.js"></script>
<script src="js/rightbuttons.js"></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
	renderFooterTemplate();
?>
</body>
</html>
<?php
db_disconnect($cn);
unset($trSt);
unset($tr_arr);
ob_end_flush();
?>