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

checkUserAndRedirectToLogin();

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');
}
session_write_close();
checkLanguage();
$cn = db_connect();
$lng = ( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : '');
$lngid = db_getLanguageID($cn, getLanguage());
$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
$contlngid = $_SESSION['user_idlanguagecontent'];
$usr_arr = GetUserIDs();
if ( GetSetting('portal','useRights',0) == 0 ){
	if( !IsUserLogin() ){
		header("Location: ".getCurPageURLWO()."/businessmodel.php");
		ob_end_flush();
		exit;
	}
} else {
	if( !IsUserLogin() ){
		header("Location: ".getCurPageURLWO()."/login.php?returl=adminpollobject.php");
		ob_end_flush();
		exit;
	}
	$cn = db_connect();
	if (!isUserAdmin() && !db_isUserAdminToPolls($cn, $usr_arr)){ 
		header("Location: ".getCurPageURLWO()."/personal.php");
		ob_end_flush();
		exit;
	}
}

$onpage = getSetting('page', 'polls.pagesize', 20);
setCookieLong('adminpollpage',ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME)));

$urlFromCookies = getCurPageURL();
if (getCookieForPage('foldergroup') !== NULL && !isset($_REQUEST['foldergroup'])) {
	$urlFromCookies = urlReplaceParam($urlFromCookies,'foldergroup', getCookieForPage('foldergroup'));
}

if (!isset($_REQUEST['answers-has']) && !isset($_REQUEST['answers-hasnot'])) {
	if (getCookieForPage('answers-hasnot') !== NULL)
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-hasnot', '');
	if (getCookieForPage('answers-has') !== NULL)
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-has', '');
	if (getCookieForPage('answers-has') === NULL && getCookieForPage('answers-hasnot') === NULL) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-hasnot', '');
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-has', '');
	}
	if( $urlFromCookies !== getCurPageURL() ){
		header("Location: ".$urlFromCookies);
		ob_end_flush();
		exit;
	}
}

if( $urlFromCookies !== getCurPageURL() ){
	header("Location: ".$urlFromCookies);
	ob_end_flush();
	exit;
}
function buildFilterButton( $name, $param, $value, $is_active, $page, $forGroup = FALSE ) {
	$url = getCurPageURL();
	return (!$forGroup ? "<span class='btn-span-separator'>" : "" )."<a href='".buildURL(urlReplaceParam($url, $param, (!$is_active ? $value : NULL )), $page )."' class='btn-top btn-top-text ".( $is_active ? "btn-top-active" : "" )."' title='".$name."'><span>".$name."</span></a>".(!$forGroup ? "</span>" : "" );
}

function buildURL( $url, $page ) {
	$url = urlReplaceParam($url,'page', $page);
	return  $url;
}


$url = getCurPageURL();
$urlWO = getCurPageURLWO();
mb_internal_encoding('UTF-8');

if (isset($_REQUEST['idbranch'])) {
	$idbranch = $_REQUEST['idbranch'];
	$skbranch = db_getSKBranch($cn,$idbranch);	
} else {
	$skbranch = db_getMainSKBranch($cn);
	$idbranch = db_getMainIDBranch($cn);	
}
$page = isset( $_GET[ "page" ] ) ? $_GET[ "page" ] : 1;
setCookieForPage('foldergroup', (isset($_REQUEST['foldergroup']) ? $_REQUEST['foldergroup'] : NULL));
setCookieForPage('answers-has', (isset($_REQUEST['answers-has']) ? 'true' : NULL));
setCookieForPage('answers-hasnot', (isset($_REQUEST['answers-hasnot']) ? 'true'  : NULL));

?>
<!doctype html>
<html>
<head>
	<title><?php echo renderTitle();?></title>
	<? 
	renderCommonMeta(renderTitle()); 
	renderCommonCSS(); 
	?>
</head>
<body>
	<?php renderModalHourGlassDiv();?>
	<div id="container">
	<header id="header-container" class="ui-layout-north">
		<?php renderLoginBlock(); ?>
	</header>
		<div id="main" role="main" class="ui-layout-center">
		<?php renderMainMenu(strtolower(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME)), FALSE); ?>
			<div id="box-tabs">
				<ul class="list-tabs">
					<?php if (isUserAdmin()) { ?>
						<li><a href="admingeneral.php"><?php getResource("button.admin.general");?></a></li>
						<li><a href="admin.php"><?php getResource("button.admin.statistic");?></a></li>
						<li><a href="adminconsole.php"><?php getResource("button.admin.console");?></a></li>
					<?php } ?>
					<li class="active"><a href="#"><?php getResource("button.admin.polls");?></a></li>
				</ul>
			</div>
		</section>
		<div id="content" class="ui-layout-center">
		<section class="box-front-bottom front-menu clearfix" style="padding-left: 0px;padding-right: 0px;">
			<div id="box-input-container" style="margin-bottom: 10px;padding-left: 10px;">
				<div class="bread-crumbs" style="padding-bottom: 5px;padding-left: 0px;"> 	
					<a href="adminpollobject.php"><?php getResource("title.polls");?></a> \ <?php echo db_getPolltypeName ($cn, $_REQUEST['idpolltype'], $contlngid).': '; if (isset($_REQUEST['skproject'])) { echo db_getProjectName($cn, $_REQUEST['skproject'], $contlngid);} else if (isset($_REQUEST['skbranch'])) { echo db_getBranchName($cn, $_REQUEST['skbranch'], $contlngid);}  ?> 
				</div>
				<div class="bread-crumbs" style="padding-bottom: 15px;padding-left: 0px;"> 	
					<hr/>
				</div>
				<div class="box-period">
					<div class="box-period-caption"><?php getResource("title.poll.mode");?></div><span><a href='#' class='btn-top btn-top-text btn-top-active' title='<?php getResource("title.poll.mode.objects");?>'><span><?php getResource("title.poll.mode.objects");?></span></a><a href='<?php echo "adminpollrespondents.php?idpolltype=".$_REQUEST["idpolltype"]."&".(isset($_REQUEST["skbranch"]) ? "skbranch=".$_REQUEST["skbranch" ] : "skproject=".$_REQUEST[ "skproject"]);?>' class='btn-top btn-top-text' title='<?php getResource("title.poll.mode.respondents");?>'><span><?php getResource("title.poll.mode.respondents");?></span></a></span>
					<div class="box-group-caption" style="margin-right: 10px;"><?php getResource("title.Group");?>&nbsp;
						<span>
							<?php 
								echo buildFilterButton(getResourceByLang("button.yes"), 'foldergroup', 'on', (!isset($_REQUEST['foldergroup']) || $_REQUEST['foldergroup'] == 'on'),  $page, TRUE );
								echo buildFilterButton(getResourceByLang("button.no"), 'foldergroup', 'off', (isset($_REQUEST['foldergroup']) && $_REQUEST['foldergroup'] == 'off'),  $page, TRUE );
							?>
						</span>
					</div>
				</div>
				<div class="box-period">
					<div class="box-period-caption" style="padding-right: 5px;"><?php getResource("title.poll.filter.answers");?></div>
					<span>
						<?php 
							echo buildFilterButton(getResourceByLang("title.poll.filter.answers.has"), 'answers-has', '', isset($_REQUEST['answers-has']),  $page );
							echo buildFilterButton(getResourceByLang("title.poll.filter.answers.hasnot"), 'answers-hasnot', '', isset($_REQUEST['answers-hasnot']),  $page );
						?>
					</span>
				</div>				

			</div>				
			<section id="box-search-in" class="clearfix">
				<form name="selfform" id="selfform" action="" method="get" >
					<section id="box-search-form">
						<div class="box-period-caption"><?php getResource("button.search");?></div><span><input type="text" id="text-search-full" style="margin-left:0px;" name="search" value="<?php  if (isset($_REQUEST['search']) && strlen($_REQUEST['search'])>0) { echo ( strlen(urldecode(urlencode(stripslashes($_REQUEST['search'])))) == strlen($_REQUEST['search']) ? urldecode(urlencode(stripslashes($_REQUEST['search']))) : urldecode(urlencode($_REQUEST['search']))); } else {echo '';}?>" placeholder="<?php getResource("message.enterText");?>"><span><button id="goSearch" class="btn-top btn-top-text" title="<?php getResource("button.search");?>"><span><?php getResource("button.search");?></span></button></span>
					</section>

					<section id="box-search-form-extended-title" class="clearfix">
						<h2><?php getResource("title.addParams");?></h2>
						<div id="btn-toggle-title" title="<?php getResource("button.hideshow");?>" <?php if(!isset($_REQUEST['hidepanel']) || $_REQUEST['hidepanel'] == '1') { print 'class="closed"';}  ?>>&uarr;&darr;</div> <!--STU -->
					</section>

					<section id="box-search-form-extended-form-container" <?php if(!isset($_REQUEST['hidepanel']) || $_REQUEST['hidepanel'] == '1') { print 'style="display:none"';}  ?> >
						<div id="box-search-form-extended-form" class="clearfix">
							<fieldset id="fieldset-place-wide">
								<legend>&nbsp;<?php getResource("field.searchPlace");?>:&nbsp;</legend>
								<div id="box-tree-search">
								<ul id="mixed">
									<img src="css/images/ajax-loader.gif"/>
									<!-- will be load by service -->
								</ul>
								</div>
							</fieldset>
						</div>

					</section>
					<input type="hidden" name="page" id="page" value="1"/>
					<input type="hidden" name="lang" id="lang" value="<?php echo getLanguage()?>"/>
					<input type="hidden" name="sessionhash" id="sessionhash" value="<?php echo substr(hash('md5', date("m.d.y ").time()), 0, 12);?>"/>
						<?php if (isset($_REQUEST['idpolltype'])) { ?>
							<input type="hidden" name="idpolltype" id="idpolltype" value="<?php echo $_REQUEST['idpolltype'];?>"/>
						<?} if (isset($_REQUEST['skproject'])) { ?>
							<input type="hidden" name="skproject" id="skproject" value="<?php echo $_REQUEST['skproject'];?>"/>
						<?} if (isset($_REQUEST['skbranch'])) { ?>
							<input type="hidden" name="skbranch" id="skbranch" value="<?php echo $_REQUEST['skbranch'];?>"/>
						<?} if (isset($_REQUEST['foldergroup'])) { ?>
							<input type="hidden" name="foldergroup" id="foldergroup" value="<?php echo $_REQUEST['foldergroup'];?>"/>
						<?} if (isset($_REQUEST['answers-hasnot'])) { ?>
							<input type="hidden" name="answers-hasnot" id="answers-hasnot" value="<?php echo $_REQUEST['answers-hasnot'];?>"/>
						<?} if (isset($_REQUEST['answers-has'])) { ?>
							<input type="hidden" name="answers-has" id="answers-has" value="<?php echo $_REQUEST['answers-has'];?>"/>
						<?} if (isset($_REQUEST['detail']) ) { ?>
							<input type="hidden" name="detail" id="detail" value="<?php echo $_REQUEST['detail'];?>"/>
						<?} if (isset($_REQUEST['detail']) && isset($_REQUEST['skpollingobject'])) { ?>
							<input type="hidden" name="skpollingobject" id="skpollingobject" value="<?php echo $_REQUEST['skpollingobject'];?>"/>
						<?} if (isset($_REQUEST['detail']) && isset($_REQUEST['skpolltype'])) { ?>
							<input type="hidden" name="skpolltype" id="skpolltype" value="<?php echo $_REQUEST['skpolltype'];?>"/>
						<?} ?> 		
				</form>
			</section>
			<section id="box-search-results" style="margin-bottom: 0px;">
			</section>
		</div>
	</div>
</div>
<div id="pollingobject-comment-dialog" class="dialog" style="min-width:600px; min-height:410px;">
	<div id="dialog-titlebar" class="titlebar"></div>
	<button class="dialog-close-button" name="close"></button>
	<div class="content-scroll-hide">
		<iframe id="pollingobject-comment-frame" name="pollingobject-comment-frame" src="" width="100%" height="100%"><?php getResource("message.notSupportFrames"); ?></iframe>			
	</div>
</div>
<?php renderModalDialogWithIframeDiv();?>
<script src="js/script.js"></script>
<script src="js/tree.js"></script>
<script src="js/libs/jquery.cookie.js"></script>
<script src="js/search.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.search.js"></script>
<script src="js/libs/drDialog/drdialog.js"></script>
<link rel="stylesheet" href='js/libs/drDialog/drdialog.css' />
<script src="js/dialoglinks.js"></script>
<script src="js/box-caption-processor.js"></script>
<script src="js/poll-extra-content-column.js"></script>
<script src="js/dialog-with-iframe.js"></script>
<script>
	var treeBuidCommandWasCall = false; 
	function clickPage(page){
    	$("#page").val(page);
    	$("#goSearch").click();
	}
	
	function loadAsyncTree(){
		// load tree 
		if (!treeBuidCommandWasCall) {
			var $serviceUrlTreePrepare = 'service/adminpolltreeprepare.php?';
			treeBuidCommandWasCall = true;
			$.ajax({
				type: "POST",
				url: $serviceUrlTreePrepare,
				dataType: "html",
				async: true,
				success: function( data ) {
					$('#mixed').html( data );
					initTrees("service/treeStructServiceSearchForPolls.php<?php echo '?'.$lng ?>", true);
					initReportsTree('',true);
					$('#mixed').find('.searchinobj').each(function() {
						if (!$(this).parent().parent().parent().find( 'li' ).length || $(this).parent().parent().parent().find('li').first().hasClass('last') ){
							$(this).attr('name', 'searchinobjlast[]');
						} else {
							$(this).attr('name', 'searchinobj[]');
						}
					});
				}
			});
		}
	}

	function loadAsyncAnswers(){
		// load answers
		var count = $("td.load-answers-section").length;
		$("td.load-answers-section").each(function() {
			var tdelement = $(this);
			var $serviceUrlAnswers = 'service/adminpollanswer.php?skpollingobject=' + $(tdelement).attr('skpollingobject') + '&skpolltype=' + $(tdelement).attr('skpolltype');
			$.ajax({
				type: "POST",
				url: $serviceUrlAnswers,
				dataType: "html",
				async: true,
				success: function( data ) {
					$(tdelement).html( data );
					--count;
					if (count == 0){ 
						initDialogLinks();
						initDialogThorough();
						if ($("#detail").length){
							$(".dialog-thorough").each(function() {
								if ($(this).attr("dialoghref") == "pollobjectanswersbyuserdetails.php?skpollingobject=<?php echo (isset($_REQUEST['skpollingobject']) ? $_REQUEST['skpollingobject'] : ''); ?>&skpolltype=<?php echo (isset($_REQUEST['skpolltype']) ? $_REQUEST['skpolltype'] : ''); ?>" ){
									$(this).click();
								}
								return false;
							});
						}
					}
				}
			});
		});
	} 

	$(document).ready(function(){
		setSearchObjectTreeEvents();
		var $serviceUrl = 'service/adminpoll.php?';

		$( "#goSearch" ).click(function() {
			$('#selfform').submit(function (){
		        return false;
		    });

			ShowGlassWindow(true);
			
			var post_data = $('#selfform').serialize();
			var $serviceUrlPrepare = 'service/adminpollprepare.php?';
			
			$.ajax({
				type: "POST",
				url: $serviceUrl + "&" + post_data,
				data: post_data,
				ataType: "html",
				async: true,
				success: function( data ) {
					ShowGlassWindow(false);
					$( "#box-search-results" ).html( data );
					initDialogThorough();
					initDialogLinks();

					$( window ).resize();
					showExtraColumns();
					loadAsyncAnswers();

					var u = removeQueryParam ("detail", document.location.href)
					var u = removeQueryParam ("skpollingobject", document.location.href)
					var u = removeQueryParam ("skpolltype", document.location.href)

					if (supportHistoryApi()) {
						history.replaceState(null, '', u);
					}
					// remove details form param 
					if ($("#detail").length){
						$("#detail").remove();
					}
					if ($("#skpollingobject").length){
						$("#skpollingobject").remove();
					}
					if ($("#skpolltype").length){
						$("#skpolltype").remove();
					}

					var settings = {};
					settings.remove = false;
					settings.caseSensitive = false;
					settings.strictly = true;
					settings.full = false;

					$.ajax({
						type: "POST",
						url: $serviceUrlPrepare + post_data,
						dataType: "html",
						success: function( data ) {
							console.log('PreparePage is done');
						}
					});
		      },
			  error: function() {
			  	 alert('inernal error!');
			     $("#box-search-results").html("");
			      ShowGlassWindow(false);
			  }
			});
		});

		$("#goSearchMin").click(function() {
			$("#text-search-full").val($("#text-search-min").val());
			$("#text-search-min").val('');
			$("#goSearch").click();
		});

		$("#text-search-min").keyup(function(e){
    		if(e.keyCode == 13)
    		{
    			$("#goSearchMin").click();
            }
        });

		$("input#checkbox_reptree_root").change(function() {
			var clname = $(this).attr("class").split(" ")[0];
			if ( clname ) {
				var selector = '#checkbox_reptree_node.'+clname;
		        $(this).parent().parent().parent().parent().parent().find(selector).prop('checked',this.checked);
		        delete selector;
		        delete clname;
			}
	    });

	    $('input#checkbox_reptree_node').change(function() {
	    	var clname = $(this).attr('class').split(' ')[0];
			if ( clname ) {
				var selector = '#checkbox_reptree_root.' + clname;
				$(this).parent().parent().parent().parent().parent().find(selector).prop('checked',false);
		        delete selector;
		        delete clname;
			}
	    });

		$("#goSearch" ).click();
		loadAsyncTree();			
	});

</script>
<?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);
ob_end_flush();
?>