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

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['notfinished']) && !isset($_REQUEST['finished'])) {
	if (getCookieForPage('notfinished') !== NULL)
		$urlFromCookies = urlReplaceParam($urlFromCookies,'notfinished', '');
	if (getCookieForPage('finished') !== NULL)
		$urlFromCookies = urlReplaceParam($urlFromCookies,'finished', '');
	if (getCookieForPage('finished') === NULL && getCookieForPage('notfinished') === NULL) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'notfinished', '');
		$urlFromCookies = urlReplaceParam($urlFromCookies,'finished', '');
	}
	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 ) {
	$url = getCurPageURL();
	return "<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></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('finished', (isset($_REQUEST['finished']) ? 'true' : NULL));
setCookieForPage('notfinished', (isset($_REQUEST['notfinished']) ? '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='<?php echo "adminpoll.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.objects");?>'><span><?php getResource("title.poll.mode.objects");?></span></a><a href='#' class='btn-top btn-top-text btn-top-active' title='<?php getResource("title.poll.mode.respondents");?>'><span><?php getResource("title.poll.mode.respondents");?></span></a></span>
				</div>

				<div class="box-period">
					<div class="box-period-caption" style="padding-right: 5px;"><?php getResource("title.poll.mode.respondents"); /*65954*/?></div>
						<span>
							<?php 
								echo buildFilterButton(getResourceByLang("title.poll.filter.finished"), 'finished', '', isset($_REQUEST['finished']),  $page );
								echo buildFilterButton(getResourceByLang("title.poll.filter.notfinished"), 'notfinished', '', isset($_REQUEST['notfinished']),  $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="sessionhash" id="sessionhash" value="<?php echo substr(hash('md5', date("m.d.y ").time()), 0, 12);?>"/>
						<input type="hidden" name="lang" id="lang" value="<?php echo getLanguage()?>"/>
							<?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['notfinished'])) { ?>
								<input type="hidden" name="notfinished" id="notfinished" value="<?php echo $_REQUEST['notfinished'];?>"/>
							<?} if (isset($_REQUEST['finished'])) { ?>
								<input type="hidden" name="finished" id="finished" value="<?php echo $_REQUEST['finished'];?>"/>
							<?} ?> 										

					</form>
				</section>
			</idv>
			<section id="box-search-results" style="margin-bottom: 0px;">
			</section>
	</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/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/adminpollrespondentstreeprepare.php?';
			treeBuidCommandWasCall = true;
			$.ajax({
				type: "POST",
				url: $serviceUrlTreePrepare,
				dataType: "html",
				success: function( data ) {
					if (data.length > 1) {
						$('#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[]');
							}
						});
					} else {
						$('#mixed').html('');
					}						
				}
			});
		}		
	}

	function initialSendButton(){
		$("#btn-send-uncompleted").unbind("click");
		$("#btn-send-uncompleted").click(function() {
			var serviceUrl = 'service/notificateUncompletedPolls.php' + window.location.search;
			$.ajax({
					type: "GET",
					url: serviceUrl,
					dataType: "html",
					success: function( data ) { 
						var msg = "<?php getResource("message.notificationwassent"); ?>";
						alert(msg);
					}
				});			
		});

	}
	function loadAsyncAnswers(){
		// load answers
		var count = $("td.load-answers-section").length;
		$("td.load-answers-section").each(function() {
			var tdelement = $(this);
			var $serviceUrlAnswers = 'service/adminpollrespondentanswer.php?idpolltype=' + $(tdelement).attr('idpolltype') + '&iduser=' + $(tdelement).attr('iduser')
				+ ($(tdelement).hasAttr('skproject') ? '&skproject=' + $(tdelement).attr('skproject') : '' )
				+ ($(tdelement).hasAttr('skbranch') ? '&skbranch=' + $(tdelement).attr('skbranch') : '' );
			$.ajax({
				type: "POST",
				url: $serviceUrlAnswers,
				dataType: "html",
				async: true,
				success: function( data ) {
					$(tdelement).html( data );
					--count;
					if (count == 0){ 
						initDialogLinks();
						initDialogThorough();
					}
				}
			});
		});
	}

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

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

			ShowGlassWindow(true);
			
			
			var post_data = $('#selfform').serialize();
			var $serviceUrlPrepare = 'service/adminpollrespondentprepare.php?';

			$.ajax({
			  type: "POST",
			  url: $serviceUrl + "&" + post_data,
			  data: post_data,
			  async: true,
			  dataType: "html",
			  success: function( data ) {
				ShowGlassWindow(false);
				$( "#box-search-results" ).html( data );
				$( window ).resize();
				loadAsyncAnswers();
				$('.discussion-sort-label').click(function() {
					event.preventDefault();
					$serviceUrl = $(this).attr("href");
					$("#goSearch").click();
				});
				initDialogLinks();
				initDialogThorough();
				initialSendButton();
			    var settings = {};
			    settings.remove = false;
			    settings.caseSensitive = false;
			    settings.strictly = true;
				settings.full = false;
				 
				$.ajax({
					type: "POST",
					url: $serviceUrlPrepare + "&" + post_data,
					data: post_data,
					dataType: "html",
					success: function( data ) {
						console.log('PreparePage is done');
					}
				});
		      },
			  error: function() {
			  	 alert('inernal error!');
			     $("#box-search-results").html("");
			      ShowGlassWindow(false);
			  }
			});

			loadAsyncTree();
		});

		$("#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();
	});

</script>
<!-- <link rel="stylesheet" href='css/jquery-ui.css' /> -->
<link rel="stylesheet" href='css/ui-lightness/jquery-ui-1.8.20.custom.css' />
<?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();
?>