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

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

$u_ids = GetUserIDs();
$usr_arr = $u_ids;
$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);	
}


?>
<!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(); ?>
		<div id="content" class="ui-layout-center">

			<section id="box-search" class="clearfix">

				<form name="selfform" id="selfform" action="" method="get">
					<section id="box-search-form">
						<label for="text-search-full"><?php getResource("button.search");?>:</label><input type="text" id="text-search-full"  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">
								<?php
									$branches = db_getBranchesRootsForTreetoUser($cn, $usr_arr, $contlngid, TRUE);
									foreach ($branches as $branch) {
										echo '<li id="'.$branch['skbranch'].'" name="'.$branch['rft_columnname_text'].'" class="root-branch"><nobr style="top:1px"><span>'.$branch['rft_columnname_text'].'</span></nobr>';
										echo '<ul>';											
										$tr_arr = db_getObjectTreetoUser($cn, 0, $usr_arr, $contlngid, $branch['skbranch']);
										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']).'" /><input type="checkbox" name="searchinobj[]" id="'.$node['idobject'].'" class="searchinobj" value="'.$node['idobject'].'" />'.$node['o_name'].'</span></nobr>';
											if (sizeof(db_getObjectTreetoSearchtoUser($cn, $node['idobject'], GetUserIDs(), $contlngid, $branch['skbranch'])) > 0){
												echo '<ul>';
												echo '	<li><span class="placeholder">&nbsp;</span></li>';
												echo '</ul>';
											}
											echo '</li>';
										}
										echo '</ul>';
										echo '</li>';
									}
									
									db_getPollsList($cn, $usr_arr, $contlngid);
									$q_st = "SELECT * FROM `pollsresult`;";
									$polls = db_runQueryAndReturnArray($cn,$q_st);
									foreach ($polls as $poll) {
										echo '<li id="'.$poll[ "skproject" ].'" name="'.$poll[ "polltype_name" ].': '.$poll[ "source_name" ].'" class="root-branch"><nobr style="top:1px"><span>'.$poll[ "polltype_name" ].': '.$poll[ "source_name" ].'</span></nobr>';
										echo '<ul>';											
										if ($poll[ "skbranch" ] != 0 ){
											$tr_arr = db_getObjectTreetoUser($cn, 0, $usr_arr, $contlngid, $poll['skbranch']);
											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']).'" /><input type="checkbox" name="searchinobj[]" id="'.$node['idobject'].'" class="searchinobj" value="'.$node['idobject'].'" />'.$node['o_name'].'</span></nobr>';
												if (sizeof(db_getObjectTreetoSearchtoUser($cn, $node['idobject'], GetUserIDs(), $contlngid, $branch['skbranch'])) > 0){
													echo '<ul>';
													echo '	<li><span class="placeholder">&nbsp;</span></li>';
													echo '</ul>';
												}
												echo '</li>';
											}
										} else {
											$branches = db_getBranchesForProject($cn, $contlngid, $poll[ "skproject" ]);
											if (sizeof($branches) > 1) {
												foreach ($branches as $branch) {
													echo '<li id="'.$branch['skbranch'].'" name="'.$branch['rft_columnname_text'].'" class="root-branch"><nobr style="top:1px"><span>'.$branch['rft_columnname_text'].'</span></nobr>';
													echo '<ul>';											
													$tr_arr = db_getObjectTreetoUser($cn, 0, $usr_arr, $contlngid, $branch['skbranch']);
													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']).'" /><input type="checkbox" name="searchinobj[]" id="'.$node['idobject'].'" class="searchinobj" value="'.$node['idobject'].'" />'.$node['o_name'].'</span></nobr>';
														if (sizeof(db_getObjectTreetoSearchtoUser($cn, $node['idobject'], GetUserIDs(), $contlngid, $branch['skbranch'])) > 0){
															echo '<ul>';
															echo '	<li><span class="placeholder">&nbsp;</span></li>';
															echo '</ul>';
														}
														echo '</li>';
													}
													echo '</ul>';
													echo '</li>';
												}
											} else {
												$tr_arr = db_getObjectTreetoUser($cn, 0, $usr_arr, $contlngid, $branches[0]['skbranch']);
												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']).'" /><input type="checkbox" name="searchinobj[]" id="'.$node['idobject'].'" class="searchinobj" value="'.$node['idobject'].'" />'.$node['o_name'].'</span></nobr>';
													if (sizeof(db_getObjectTreetoSearchtoUser($cn, $node['idobject'], GetUserIDs(), $contlngid, $branches[0]['skbranch'])) > 0){
														echo '<ul>';
														echo '	<li><span class="placeholder">&nbsp;</span></li>';
														echo '</ul>';
													}
													echo '</li>';
												}
											}
										}
										echo '</ul>';
										echo '</li>';
									}


								?>
								</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()?>"/>
				</form>

				<section id="box-search-results">
				</section>
		</div>
	</div>
</div>
<script src="js/script.js"></script>
<script src="js/libs/jquery.cookie.js"></script>
<script src="js/tree.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/jquery.highlight.js"></script>
<script>
	function clickPage(page){
    	$("#page").val(page);
    	$("#goSearch").click();
    }

	$(document).ready(function(){
		initTrees("service/treeStructServiceSearch.php<?php echo '?'.$lng ?>", true);
		setSearchObjectTreeEvents();
		initReportsTree('',true);
		$serviceUrl = 'service/discussionsService.php?';

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

			ShowGlassWindow(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[]');
	   			}
  			});
  			var post_data = $('#selfform').serialize();
			$.ajax({
				type: "POST",
				url: $serviceUrl + "&" + post_data,
				data: post_data,
				dataType: "html",
				success: function( data ) {
					ShowGlassWindow(false);
					$( "#box-search-results" ).html( data );
					$( window ).resize();
					$('.discussion-sort-label').click(function() {
						event.preventDefault();
						$serviceUrl = $(this).attr("href");
						$("#goSearch").click();
					});
					var settings = {};
					settings.remove = false;
					settings.caseSensitive = false;
					settings.strictly = true;
					settings.full = false;
		      },
			  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();
	});

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